$m(function (args) {
    var $this = $(this.element).closest("body");
    //用于刷新服务状态的按钮状态
    var myOp = "";
    //用于刷新状态的服务id
    var myId = "";
    //用于刷新状态的参数集合
    var myParam;
    //编辑状态
    var editStatus = {
        serviceInfo: false,
        messageInfo: false,
        envInfo: false,
        limit: false,
        flowParams: false
    };

    //获取到流程发布服务控制器
    var controller = new MinePublishServiceController(themeId);
    controller.serviceDialog = $this.find('.app-config-container');
    controller.service = {};
    controller.service.id = serviceId;
    controller.service.themeId = themeId;

    var $that = $this.find('.app-config-container');

    //国际化
    var locale = TempoUtils.locale;

    //服务类型
    var types = {
        async: TempoUtils.locale("mine.yibu"),
        sync: TempoUtils.locale("mine.tongbu"),
        stream: TempoUtils.locale("mine.liu")
    };

    //授权数据
    var authData = {
        removeIds: [],
        addIds: []
    };

    //执行模式
    var EXCUTE_MODE = {
        "SYNC_ON_LOCAL": '本地',
        "SYNC_ON_YARN": '集群',
        "SYNC_ON_K8S": 'k8s',
        "本地": "SYNC_ON_LOCAL",
        "集群": "SYNC_ON_YARN",
        "k8s": "SYNC_ON_K8S"
    };

    //请求参数
    var REQUEST_PARAMETERS = [
        {
            name: "App-Key",
            desc: TempoUtils.locale("mine.appkey_description")
        },
        {
            name: "App-Token",
            desc: TempoUtils.locale("mine.appsecret_description")
        },
        {
            name: "serviceId",
            desc: TempoUtils.locale("mine.fwid")
        },
        {
            name: "method",
            desc: TempoUtils.locale("mine.methoddescription")
        },
        {
            name: "eid",
            desc: TempoUtils.locale("mine.eiddescription")
        },
        {
            name: "data",
            desc: TempoUtils.locale("mine.request_data")
        },
        {
            name: "flowParams",
            desc: TempoUtils.locale("mine.request_flowparams")
        }
    ];

    //相应参数
    var RESPONSE_PARAMETERS = [
        {
            name: "status",
            desc: TempoUtils.locale("mine.statusdescription")
        },
        {
            name: "message",
            desc: TempoUtils.locale("mine.errordescription")
        },
        {
            name: "code",
            desc: TempoUtils.locale("mine.codedescription")
        },
        {
            name: "eid",
            desc: TempoUtils.locale("mine.eidreturndesc")
        },
        {
            name: "data",
            desc: TempoUtils.locale("mine.response_data")
        }
    ];

    var $appConfig = controller.serviceDialog;

    //顶部
    var $containerTop = $appConfig.find('div[id="' + row.id + '"][class="app-config-container-top"]');

    //服务信息
    var $serviceInfo = $appConfig.find("#service-info");
    var serviceGrid = $serviceInfo.find(".app-config-service-info-form");

    //授权信息
    var $license = $appConfig.find(".license-info");
    var authGrid = $license.find('#license-info-table');

    //实例列表
    var $instance = $appConfig.find(".instance-info");
    var instanceGrid = $instance.find('#instance-info-table');

    //消息信息
    var $message = $appConfig.find(".message-info");
    var messageGrid = $message.find('#message-info-table');

    //环境参数
    var $env = $appConfig.find(".env-info");
    var envTable = $env.find('.env-info-table');

    //资源使用情况
    var $resource = $appConfig.find(".resource-info");
    var resourceGrid = $resource.find(".app-config-resource-info-form");

    //python资源限制
    var $limitInfo = $appConfig.find(".limit-info");
    var limitGrid = $limitInfo.find('#tempo-mine-flow-limit-info');

    //流程参数
    var $paramInfo = $appConfig.find(".flowparam-info");
    var paramGrid = $paramInfo.find('#flowparam-info-table');

    //请求参数
    var $requestInfo = $appConfig.find(".request-info");
    var requestGrid = $requestInfo.find('#request-info-table');

    //相应参数
    var $responseInfo = $appConfig.find(".response-info");
    var responseGrid = $responseInfo.find('#response-info-table');

    var getFlowArray = function () {
        return resPar.filter(function (v) {
            if (v === null) {
                return false;
            }
            if (v.paramName === "system.appId" || v.$configResources$ || v.$configStreamServiceInfo$) {
                return false;
            } else {
                return true;
            }
        });
    };

    //流程参数
    var flowArray = getFlowArray();

    var constFlowParams = TempoMineUtils.getConstFlowParams();

    var dataSourceCache = {};

    /**
     * 更新状态
     * @param op
     * @param id
     */
    var updateMyStatus = function (op, id) {
        var myInterval = setInterval(function () {
            if (myId != "") {
                $.postJson({
                    url: contextPath + '/api/ai/app/model/status/' + myId,
                    data: {
                        requestId: myId
                    },
                    success: function (d) {
                        var status = d.data;
                        if (op == "start" && status == "RUNNING") {
                            //已启动
                            $('span[id="' + myId + '"][class="task-runtStatus"]').text(locale('aiview.status-running'));
                            //重新获取$containerTop，防止切换页签后元素丢失
                            $containerTop = $('div[id="' + row.id + '"][class="app-config-container-top"]');
                            $containerTop.find('a.start-button').text(TempoUtils.locale("aiview.serviceStop"));
                            $containerTop.find('a.start-button').removeClass("ui-state-disabled").attr("disabled", false);
                            Eventbus.trigger('updateserviceStatus.service', locale('aiview.status-running'), myId);
                            clearInterval(myInterval);
                            myInterval = null;
                            myId = "";
                        } else if (op == "start" && status == "STARTING") {
                            //启动中
                            $('span[id="' + myId + '"][class="task-runtStatus"]').text(locale('aiview.status-starting'));
                            Eventbus.trigger('updateserviceStatus.service', locale('aiview.status-starting'), myId);
                        } else {
                            if ((status == "NONE" || status == null) && op == "stop") {
                                $('span[id="' + myId + '"][class="task-runtStatus"]').text(locale('aiview.status-none'));
                                Eventbus.trigger('updateserviceStatus.service', locale('aiview.status-none'), myId);
                                clearInterval(myInterval);
                                myInterval = null;
                                myId = "";
                            } else if ((status == "NONE" || status == null) && op == "start") {
                                $('span[id="' + myId + '"][class="task-runtStatus"]').text(locale('aiview.status-none'));
                                //重新获取$containerTop，防止切换页签后元素丢失
                                $containerTop = $('div[id="' + row.id + '"][class="app-config-container-top"]');
                                $containerTop.find('a.start-button').text(TempoUtils.locale("aiview.serviceStart"));
                                $containerTop.find('a.start-button').removeClass("ui-state-disabled").attr("disabled", false);
                                row.launchState = "NONE";
                                Eventbus.trigger('updateserviceStatus.service', locale('aiview.status-none'), myId);
                                clearInterval(myInterval);
                                myInterval = null;
                                myId = "";
                            }
                        }
                    },
                    error: function (e) {

                    }
                });
            }
        }, 2000);
        window.publishTaskStatusInterval = myInterval;
    }

    /**
     * 初始化页面顶部
     * 同步服务：开启、点击测试、下载按钮
     * 异步服务：点击测试、下载按钮
     * 流：开启
     */
    var initContainerTopPage = function () {
        if (row.type && row.type == "async") {
            $containerTop.find('a.start-button').remove();
        } else if (row.type && row.type == "stream") {
            $containerTop.find("#app-config-download").remove();
            $containerTop.find("a.test-button").remove();
        }
        if (row.type && (row.type === "stream" || row.type === "sync")) {
            if (!!row.launchState && row.launchState != 'NONE') {
                if (row.launchState == 'STARTING') {
                    //启动中
                    $('div[objid="' + row.id + '"] #service_status').text(locale('aiview.status-starting'));
                    $containerTop.find('a.start-button').text(TempoUtils.locale("aiview.serviceStart"));
                    $containerTop.find('a.start-button').addClass("ui-state-disabled").attr("disabled", true);
                } else if (row.launchState == 'RUNNING') {
                    //已启动
                    $('div[objid="' + row.id + '"] #service_status').text(locale('aiview.status-running'));
                    $containerTop.find('a.start-button').text(TempoUtils.locale("aiview.serviceStop"));
                    $containerTop.find('a.start-button').addClass("ui-state-disabled").attr("disabled", false);
                }
            } else {
                //未启动
                $('div[objid="' + row.id + '"] #service_status').text(locale('aiview.status-none'));
                $containerTop.find('a.start-button').text(TempoUtils.locale("aiview.serviceStart"));
            }
        }
    };


    /**
     * 绑定页面顶部的事件
     */
    var bindContainerTopEvent = function () {
        if (row.type && row.type != "stream") {
            $containerTop.find('a.download-button').button();
            $containerTop.find('a.test-button').button({
                click: function (e) {

                    var eventName = '';
                    if (row.type == 'sync') {
                        eventName = 'testSyncFlowMutual.mine';
                    } else if (row.type == 'async') {
                        eventName = 'testASyncFlowMutual.mine';
                    }
                    if (eventName) {
                        var func = arguments.callee;
                        var ready = Eventbus.triggerHandler("ready.serviceTest")[0];
                        if (ready) {
                            Eventbus.trigger(eventName, row);
                        } else {
                            console.log("wait for init event. serviceTest");
                            setTimeout(func, 200);
                        }
                    }
                }
            });

            if ($containerTop.find("#app-config-download") && $containerTop.find("#app-config-download").length > 0) {
                //普通流程发布的服务
                var commonName = "公共包";
                var commonUrl = contextPath + "/api/ai/mine/sync/downloadRuntimeJars";
                var servieName = "服务包";
                var serviceUrl = contextPath + "/api/ai/mine/sync/download-sync-by-mac-address";
                //管道流程发布的服务
                if (row.flowType && row.flowType == "plflow") {
                    commonName = "管道公共包";
                    commonUrl = contextPath + "/api/ai/mine/sync/download-mleap-runtime-jar";
                    servieName = "管道服务包";
                    serviceUrl = contextPath + "/api/ai/mine/sync/download-mleap-by-mac-address";
                }
                Vue.use(httpVueLoader);
                new Vue({
                    el: '#app-config-download',
                    data: function () {
                        return {
                            type: window.row.type,
                            items: {
                                async: [
                                    {
                                        id: "sdk",
                                        name: "SDK",
                                        divided: false,
                                        url: contextPath + '/api/ai/mine/sync/sdk',
                                        data: {
                                            id: row.id
                                        }
                                    },
                                    {
                                        id: "javaCode",
                                        name: "Java示例代码",
                                        divided: false,
                                        url: contextPath + '/api/ai/mine/async/clientcode',
                                        data: {
                                            id: row.id,
                                            flowid: row.flowid
                                        }
                                    },
                                    {
                                        id: "jsCode",
                                        name: "JS示例代码",
                                        divided: true,
                                        url: contextPath + '/api/ai/mine/async/jscode',
                                        data: {
                                            id: row.id,
                                            flowid: row.flowid
                                        }
                                    },
                                    {
                                        id: "pythonCode",
                                        name: "Python示例代码",
                                        divided: true,
                                        url: contextPath + '/api/ai/mine/async/pycode',
                                        data: {
                                            id: row.id,
                                            flowid: row.flowid
                                        }
                                    }
                                ],
                                sync: [
                                    {
                                        id: "sdk",
                                        name: "SDK",
                                        divided: false,
                                        url: contextPath + '/api/ai/mine/sync/sdk',
                                        data: {
                                            id: row.id
                                        }
                                    },
                                    {
                                        id: "javaCode",
                                        name: "Java示例代码",
                                        divided: false,
                                        url: contextPath + '/api/ai/mine/sync/clientcode',
                                        data: {
                                            id: row.id,
                                            flowid: row.flowid
                                        }
                                    },
                                    {
                                        id: "jsCode",
                                        name: "JS示例代码",
                                        divided: true,
                                        url: contextPath + '/api/ai/mine/sync/jscode',
                                        data: {
                                            id: row.id,
                                            flowid: row.flowid
                                        }
                                    },
                                    {
                                        id: "pythonCode",
                                        name: "Python示例代码",
                                        divided: true,
                                        url: contextPath + '/api/ai/mine/sync/pycode',
                                        data: {
                                            id: row.id,
                                            flowid: row.flowid
                                        }
                                    },
                                    {
                                        id: "common",
                                        name: commonName,
                                        divided: true,
                                        url: commonUrl,
                                        data: {}
                                    },
                                    {
                                        id: "service",
                                        name: servieName,
                                        divided: false,
                                        url: serviceUrl,
                                        data: {}
                                    }
                                ],
                                stream: 'none'
                            }
                        }
                    },
                    methods: {
                        beforeHandleCommand: function (url, data) {
                            return {
                                "url": url,
                                "data": data
                            }
                        },

                        /**
                         * 下载
                         */
                        download: function (command) {
                            var url = command.url;
                            var data = command.data;
                            //下载离线服务包弹窗
                            if (url == serviceUrl) {
                                setTimeout(function () {
                                    modelDownLoadLimitCheck(url);
                                }, 300);
                            } else {
                                TempoUtils.downLoadFile({
                                    url: url,
                                    data: data,
                                    method: 'get'
                                });
                            }
                        }
                    }
                });
            }
        }

        /**
         * 启动流/同步服务
         */
        var operateStart = function () {
            var that = $that;
            //服务启动模式
            var mode = envTable.find('select[name=mode-select]').selectmenu("getValue");
            //线程数/管理CPU个数
            var cpu = envTable.find('input[name=manage-cpu-num-input]').val();
            //内存（GB）/管理内存（GB）
            var mem = envTable.find('input[name=manage-memory-input]').val();
            //执行器个数
            var exeProcessNum = envTable.find('input[name=executor-num-input]').val();
            //运行CPU个数
            var totalExecutorCores = envTable.find('input[name=run-cpu-num-input]').val();
            //运行内存（GB）
            var executorMemory = envTable.find('input[name=run-memory-input]').val();
            //管理GPU个数
            var gpu = envTable.find('input[name=gpu]').val();
            //缓存设置
            var cacheType = envTable.find('select[name=cache-config-select]').selectmenu("getValue");
            //Python资源限制CPU个数
            var limitExtendCpu = limitGrid.find('input[name=limitExtendCpuInput]').val();
            //Python资源限制内存(GB)
            var limitExtendMemory = limitGrid.find('input[name=limitExtendMemoryInput]').val();
            operateFlow.apply(that, [row, {
                mode: mode,
                cpu: cpu,
                mem: mem,
                exeProcessNum: exeProcessNum,
                totalExecutorCores: totalExecutorCores,
                executorMemory: executorMemory,
                gpu: gpu,
                cacheType: cacheType,
                limitExtendCpu: limitExtendCpu,
                limitExtendMemory: limitExtendMemory,
            }]);
        };

        /**
         *  输入MAC校验规则
         *
         * @param paramDialog 弹框dom元素
         */
        var macValid = function (paramDialog) {
            var inputDom = paramDialog.find("#inputMacAddress");
            inputDom.validatebox({
                required: true,
                autofill: false,
                customValidate: function (value) {
                    if ($.trim(value) == "") {
                        //当不填写MAC地址时，会提示"此项为必填项"
                        $(this).validatebox("setOptionsTip", TempoUtils.locale("aiview.mac_required"));
                        return false;
                    }
                    //MAC地址校验规则：支持纯字符MAC地址，若中间存在分割符号，支持以英文中划线或英文冒号分割
                    var regex = "(([A-Fa-f0-9]{2}-){5}[A-Fa-f0-9]{2})|(([A-Fa-f0-9]{2}:){5}[A-Fa-f0-9]{2})|^([0-9a-fA-F]{2})(([0-9a-fA-F]{2}){5})$";
                    //RegExp对象用于存储检索模式
                    var regexp = new RegExp(regex);
                    //test()方法用来检测字符串是否匹配正则表达式
                    if (!regexp.test($.trim(value)) || $.trim(value).length > 17) {
                        //请输入正确的MAC地址
                        $(this).validatebox("setOptionsTip", TempoUtils.locale("aiview.macValid"));
                        return false;
                    }
                    return true;
                }
            })
        }

        /**
         * 进行模型下载限制校验
         *
         * @param url       接口地址
         * @param callback  数据回填
         */
        var modelDownLoadLimitCheck = function (url, callback) {
            //进行模型下载限制校验
            //遮罩层
            var process = $("<div/>").tempoprogressbar();
            $.ajax({
                url: contextPath + '/api/ai/model/download/limit/download-check',
                data: {
                    moduleName: 'model-offline-download',
                },
                type: 'POST',
                success: function (result) {
                    if (result.success) {
                        if (result.data) {
                            //总次数
                            var sumDownloadNum = result.data.sumDownloadNum;
                            //已下载次数
                            var alreadyDownloadNum = result.data.alreadyDownloadNum;
                            //剩余下载次数
                            var restDownloadNum = result.data.restDownloadNum;
                            var paramDialog = $('<div class="mine-down-model-dialog"/></div>');
                            paramDialog.dialog({
                                title: "下载" + servieName,
                                width: 500,
                                height: 321,
                                //设置弹窗无法调整大小
                                resizable: false,
                                //将窗体显示为模式化窗口
                                modal: true,
                                close: function () {
                                    paramDialog.dialog('destroy');
                                },
                                open: function () {
                                    paramDialog.append(
                                        "<div id='mac_input_box'>" +
                                        "<form><tr><td><span style='padding: 3px;color: red;'>" + "*" + "</span>" +
                                        "<label class='theme_operate_input_mac'>" + TempoUtils.locale("aiview.macAddress") + "</label></td>" +
                                        "<td><input placeholder='" + TempoUtils.locale("aiview.input_macAddress") + "' type='text' id='inputMacAddress' ></td>" +
                                        "</tr></form></div>" +
                                        "<div id='downloadExplain'>" +
                                        "<p><span>" + TempoUtils.locale("aiview.downloadExplain") + "</span></p>" +
                                        "<p><span>相同模型使用同一MAC，只计一次。总计" + sumDownloadNum + "次，已下载" + alreadyDownloadNum + "次，剩余" + restDownloadNum + "次。</span></p>" +
                                        "</div>");
                                },
                                buttons: [
                                    {
                                        text: TempoUtils.locale("mine.publish-dialog-cancel"),
                                        id: "tempo-mine-down-service-cancel",
                                        click: function () {
                                            paramDialog.dialog('destroy');
                                        }
                                    },
                                    {
                                        text: TempoUtils.locale("mine.publish-dialog-sure"),
                                        id: "tempo-mine-limit-model-download-by-mac-address-confirm",
                                        click: function () {
                                            //点击确定弹出确认MAC地址弹窗
                                            confirmMacAddressDialog(paramDialog, url, result)
                                        }
                                    }
                                ]
                            });
                            //调用MAC地址校验规则
                            macValid(paramDialog);
                            //回填MAC地址
                            if (callback) {
                                callback();
                            }
                        } else {
                            //无数据则说明不需要对离线模型进行下载限制，直接下载
                            TempoUtils.downLoadFile({
                                url: url,
                                data: {
                                    serviceId: row.id
                                },
                                method: 'get'
                            });
                        }
                    } else {
                        //接口调用报错提示
                    }
                },
                complete: function () {
                    process.tempoprogressbar("destroy");
                },
                error: function () {
                }
            });
        };

        /**
         *
         * @param paramDialog   父弹窗
         * @param url           下载服务包接口地址
         * @param result        离线模型下载接口返回的结果数据(下载次数、已下载次数等)
         */
        var confirmMacAddressDialog = function (paramDialog, url, result) {
            //获取MAC地址校验结果
            var form = paramDialog.find("form");
            //如果校验成功进入确认MAC地址界面
            if (!form.formValidate()) {
                return;
            } else {
                //确定MAC信息弹窗
                var macMessageDialog = $('<div class="mine-mac-message-dialog"/></div>');
                //获取填写的MAC地址
                var macAddress = paramDialog.find("#inputMacAddress").val();
                //重新设置MAC地址格式
                macAddress = setMacAddress(macAddress);
                macMessageDialog.dialog({
                    title: "提示",
                    width: 400,
                    height: 212,
                    //弹窗无法调整大小
                    resizable: false,
                    modal: true,
                    close: function () {
                        //点击取消全部关闭
                        macMessageDialog.dialog('destroy');
                    },
                    open: function () {
                        macMessageDialog.append(
                            "<div class='mac_confirmation_message_dialog'>" +
                            "<p><span>" + TempoUtils.locale("aiview.mac_confirmation_message") + "</span></p>" +
                            "<p><span>MAC地址：" + macAddress + "</span></p>" +
                            "</div>"
                        );
                    },
                    buttons: [
                        {
                            //返回
                            text: TempoUtils.locale("aiview.reverseBack"),
                            click: function () {
                                //销毁确认MAC地址弹窗
                                macMessageDialog.dialog('destroy');
                                //点击返回，销毁MAC确认弹窗，显示输入MAC弹窗
                                modelDownLoadLimitCheck(url, function () {
                                    //MAC地址回填
                                    $("#inputMacAddress").validatebox("setValue", macAddress);
                                });
                            }
                        },
                        {
                            //确定
                            text: TempoUtils.locale("aiview.confirm"),
                            id: "tempo-mine-limit-model-download-by-mac-address-confirm",
                            click: function () {
                                var downloadData = result.data;
                                //校验是否能够下载
                                notDownloadDialog(paramDialog, downloadData, url);
                                macMessageDialog.dialog('destroy');
                            }
                        }
                    ]
                });
                //销毁弹窗
                paramDialog.dialog('destroy');
            }
        };

        /**
         *
         * @param paramDialog   父类弹窗
         * @param downloadData  弹窗展示所需要的数据(下载总次数、已下载次数等)
         * @param url           下载服务包接口地址
         */
        var notDownloadDialog = function (paramDialog, downloadData, url) {
            //总次数
            var sumDownloadNum = downloadData.sumDownloadNum;
            //已下载次数
            var alreadyDownloadNum = downloadData.alreadyDownloadNum;
            //剩余下载次数
            var restDownloadNum = downloadData.restDownloadNum;
            //获取填写的MAC地址
            var macAddress = paramDialog.find("#inputMacAddress").val();
            //重新设置MAC地址格式
            macAddress = setMacAddress(macAddress);
            $.ajax({
                //判断能否进行下载
                url: contextPath + '/api/ai/model/download/limit/mac-licence-check',
                data: {
                    moduleName: 'model-offline-download',
                    serviceId: row.id,
                    macAddress: macAddress,
                },
                type: 'POST',
                success: function (result) {
                    //下载次数充足可进行下载
                    if (result.success) {
                        TempoUtils.downLoadFile({
                            url: url,
                            data: {
                                serviceId: row.id,
                                macAddress: macAddress,
                            },
                            method: 'get'
                        });
                    } else {
                        //无法下载弹窗页面
                        var cannotDownloadDialog = $('<div class="mine-cannot-download-dialog"/></div>');
                        cannotDownloadDialog.dialog({
                            title: "提示",
                            width: 400,
                            height: 212,
                            //弹窗无法调整大小
                            resizable: false,
                            modal: true,
                            close: function () {
                                //点击取消全部关闭
                                cannotDownloadDialog.dialog('destroy');
                            },
                            open: function () {
                                if (restDownloadNum <= 0) {
                                    cannotDownloadDialog.append(
                                        "<div class='mac_cannot_download_dialog'>" +
                                        "<p><span style='font-size: 14px;'>" + TempoUtils.locale("aiview.cannotDownload") + "</span></p>" +
                                        "<p><span>总计" + sumDownloadNum + "次，已下载" + alreadyDownloadNum + "次，剩余" + restDownloadNum + "次。</span></p>" +
                                        "</div>"
                                    );
                                }
                            },
                            buttons: [
                                {
                                    //返回
                                    text: TempoUtils.locale("aiview.reverseBack"),
                                    click: function () {
                                        //销毁无法下载弹窗
                                        cannotDownloadDialog.dialog('destroy');
                                        //展示填写MAC弹窗并回填MAC地址
                                        modelDownLoadLimitCheck(url, function () {
                                            //MAC地址回填
                                            $("#inputMacAddress").validatebox("setValue", macAddress);
                                        });
                                    }
                                },
                                {
                                    //确定
                                    text: TempoUtils.locale("aiview.confirm"),
                                    id: "tempo-mine-limit-model-download-by-mac-address-confirm",
                                    click: function () {
                                        //点击确定销毁弹窗
                                        cannotDownloadDialog.dialog('destroy');
                                    }
                                }
                            ]
                        })
                    }
                }
            })
        };

        /**
         * 将MAC地址以大写字母加英文冒号返回
         *
         * @param macAddress 填写的MAC地址
         * @returns {null|string|*}
         */
        var setMacAddress = function (macAddress) {
            //保存重新设置后的MAC地址
            var mac = "";
            if (macAddress != null) {
                //将MAC地址设置为大写字母
                var macAddress = macAddress.toUpperCase();
                if (macAddress.indexOf('-') > -1 || macAddress.indexOf(':') > -1) {
                    //将”-“全部替换，g表示全部替换
                    var reg = new RegExp("-", "g");
                    mac = macAddress.replace(reg, ":");
                } else {
                    //通过循环给为纯字符MAC地址添加英文冒号
                    for (var i = 0; i < macAddress.length; i++) {
                        mac += macAddress[i];
                        if (i % 2 === 1) {
                            mac += ":";
                        }
                    }
                    mac = mac.substring(0, mac.length - 1);
                }
                return mac;
            }
            return;
        };

        /**
         * 启动或停止
         * @param row
         * @param setting
         */
        var operateFlow = function (row, setting) {
            var requestId = null;
            if (authCodes.length != 0) {
                requestId = window.btoa(authCodes[0].clientCode + "#" + authCodes[0].skCode + "#" + new Date().getTime());
            } else {
                requestId = window.btoa(new Date().getTime());
            }
            var id = row.id, flowid = row.flowid, status = row.launchState;
            var flowParam = "[]";
            if (flowArray != undefined && flowArray != null) {
                flowParam = JSON.stringify(flowArray);
            }
            var param = {
                mode: setting.mode || row.mode,
                cpu: setting.cpu || 2,
                mem: setting.mem || 2,
                //执行器个数
                exeProcessNum: setting.exeProcessNum || 1,
                //运行CPU个数
                totalExecutorCores: setting.totalExecutorCores || 2,
                //运行内存（GB）
                executorMemory: setting.executorMemory || 2,
                //管理GPU个数
                gpu: setting.gpu || 0,
                //缓存设置
                cacheType: setting.cacheType || "MEMORY_AND_DISK",
                //Python资源限制CPU个数
                limitExtendCpu: setting.limitExtendCpu || 2,
                //Python资源限制内存(GB)
                limitExtendMemory: setting.limitExtendMemory || 2,
                requestId: requestId,
                //流程参数
                flowparam: flowParam,
            };
            myParam = param;

            var counter = status == 'RUNNING' ? 25 : 0;
            // 最终服务应该呈现的状态
            var finalTag = (status == 'RUNNING' || status == 'STARTING') ? false : true;
            var op = finalTag ? "start" : "stop";
            myOp = op;
            myId = id;
            if (op == "stop") {
                param = {
                    requestId: requestId,
                };
            }
            //点击启动按钮或者停止按钮后，直接禁用按钮
            $containerTop.find('a.start-button').addClass("ui-state-disabled").attr("disabled", true);
            updateMyStatus(op, myId);
            //增加遮罩，防止快速点击多次启动停止
            var process = $("<div/>").tempoprogressbar();
            $.postJson({
                url: contextPath + '/api/ai/app/model/' + op + "/" + id,
                data: param,
                success: function (d) {
                    var serviceStatus = "";
                    if (!d.success) {
                        $("<div/>").alert({msg: d.message});
                        //启动或停止失败，需要解除禁用状态。
                        $containerTop.find('a.start-button').removeClass("ui-state-disabled").attr("disabled", false);
                        return;
                    }
                    if (op == "start") {
                        $('div[objid="' + id + '"] #ca-status').text(TempoUtils.locale("aiview.serviceStarting"));
                        $("div[objid='" + id + "'] #service_status").text(TempoUtils.locale("aiview.serviceStarting"));
                        serviceStatus = TempoUtils.locale("aiview.serviceStarting");
                    } else if (op == "stop") {
                        $('div[objid="' + id + '"] #ca-status').text("停止中");
                        serviceStatus = "停止中";
                        Eventbus.trigger('updateserviceStatus.service', serviceStatus, id);
                        $containerTop.find('a.start-button').addClass("ui-state-disabled").attr("disabled", true);
                    }
                    updateStatus(op, finalTag, serviceStatus, counter);
                },
                complete: function () {
                    process.tempoprogressbar("destroy");
                }
            });
        };

        //同步服务/流服务点击启动
        if ("async" !== row.type) {
            $containerTop.find('a.start-button').button({
                click: function (e) {
                    if (!checkBlockStatus("无法启动服务")) {
                        return;
                    }
                    if (row.type == 'sync' || row.type == 'stream') {
                        if (!!row.launchState && row.launchState != 'NONE') {
                            var msg = TempoUtils.locale("mine.shifotingzhitongbufuwu");
                            if (row.type == "stream") {
                                msg = TempoUtils.locale("mine.shifotingzhiliufuwu");
                            }
                            $("<div/>").confirm({
                                title: TempoUtils.locale("mine.prompt"),
                                msg: msg,
                                ok: function () {
                                    $containerTop.find('a.start-button').addClass("ui-state-disabled").attr("disabled", true);
                                    //启动操作
                                    operateStart();
                                }
                            })
                        } else {
                            if (row.type == 'sync') {
                                if (authCodes == null || authCodes && authCodes.length == 0) {
                                    TempoUtils.showTip(TempoUtils.locale("aiview.configtip2"));
                                    return;
                                }
                            }
                            //启动操作
                            operateStart();
                        }
                    }
                }
            });
        }
    };

    /**
     * 初始化页面顶部
     */
    var initContainerTop = function () {
        initContainerTopPage();
        bindContainerTopEvent();
    };

    /**
     * 加载服务别名
     */
    var loadServiceAlias = function () {
        var alias = serviceGrid.find('td[name="async-test-data-alias"]');
        var lines = "";
        if (row.serviceAlias == null || row.serviceAlias.length == 0 || "" == row.serviceAlias) {
            alias.html(TempoUtils.locale('aiview.alias'));
        } else {
            if (row.type == 'async') {
                lines = urlPrefix + "/webapi/ai/model/alias/async/execute/" + row.serviceAlias;
            } else if (row.type == 'sync') {
                lines = urlPrefix + "/webapi/ai/model/alias/sync/" + row.serviceAlias;
            }
            var str = "";
            var line = row.serviceAlias;
            line += "<a class='app-key-copy-btn' onclick='copyToClip(\"{line}\")'>[" + locale("mine.copy_address") + "]</a>"
            line += "<br/>";
            line = line.replace("{line}", lines);
            str += line;
            alias.html(str);
        }
    };

    /**
     * 更新头部的服务状态
     * @param id 服务ID
     * @param updateFn 回调函数
     * @param type 服务类型
     */
    var updateStatusLoop = function (id, updateFn, type) {
        //Eventbus.trigger('updateStatusLoop.service', id, updateFn, type);
    };

    /**
     * 初始化服务配置页面
     * @param rowData
     */
    var initServiceInfoPage = function (rowData) {
        //设置服务类型
        $that.find(".service-type").text(types[rowData.type]);
        if (rowData.type == 'stream') {
            //移除流服务使用的其它服务信息
            $this.find(".sync-api-desc").remove();
            $this.find(".async-api-desc").remove();
            //显示流服务服务信息
            $this.find(".stream-api-desc").show();
            //获取流服务服务信息配置的参数
            var configStreamServiceInfo = resPar.filter(function (v) {
                if (v.$configStreamServiceInfo$ != null) {
                    return true;
                }
            });
            if (configStreamServiceInfo.length > 0) {
                var json = JSON.parse(configStreamServiceInfo[0]["$configStreamServiceInfo$"]);
                if (Object.keys(json).length == 0) {
                    return false;
                }
                //初始化提示信息
                TempoMineUtils.initPromptInfo(serviceGrid.find("#tempo-consumption-num-dis-info"),
                    "tempo-consumption-num-help-info", "勾选后可以设置每次消费的数据上限，若不勾选则系统每次获取消息读取时间内的全部数据执行",
                    '520px', '18px', -20, 20);
                //初始化设置消费条数按钮
                var consumptionNumDom = serviceGrid.find("#tempo-consumption-num");
                consumptionNumDom.checkbox({
                    change: function (event, data) {
                        var dataOnlineLabelDom = serviceGrid.find("#tempo-data-online-label");
                        var dataOnlineInputDom = serviceGrid.find("input[name='tempo-data-online']");
                        if (data.checked) {
                            dataOnlineLabelDom.show();
                            //显示进行校验
                            dataOnlineInputDom.numberbox("doValidate");
                            dataOnlineInputDom.show();
                        } else {
                            dataOnlineLabelDom.hide();
                            //隐藏前校验未通过恢复默认值
                            if (!dataOnlineInputDom.numberbox("validate")) {
                                dataOnlineInputDom.val(10);
                                dataOnlineInputDom.numberbox("doValidate");
                            }
                            dataOnlineInputDom.hide();
                        }
                    }
                });
                //设置消费条数
                consumptionNumDom.checkbox('option', 'checked', json.setConsumptionNum == "true");
                consumptionNumDom.attr("disabled", true);
                //初始化数据上线（条）输入框
                var dataOnlineLabelDom = serviceGrid.find('#tempo-data-online-label');
                var dataOnlineInputDom = $('<input name="tempo-data-online" style="margin-left: 20px;"/>')
                    .val(json.dataOnline || 10).insertAfter(dataOnlineLabelDom);
                dataOnlineInputDom.numberbox({
                    width: 'calc(100% - 253px)',
                    range: '[1, 10000]',
                    validator: true,
                    required: true,
                    autofill: false,
                    precision: 0
                });
                dataOnlineInputDom.addClass("ui-state-disabled").attr("disabled", true);
                //设置消费条数未勾选，隐藏数据上限输入框
                if (json.setConsumptionNum != "true") {
                    dataOnlineLabelDom.hide();
                    dataOnlineInputDom.hide();
                }
                //初始化消息读取时间（ms）输入框
                var messageReadingTimeLabelDom = serviceGrid.find('#tempo-message-reading-time-label');
                var messageReadingTimeInputDom = $('<input name="tempo-message-reading-time" style="margin-left: 15px;"/>')
                    .val(json.messageReadingTime || 1000).insertAfter(messageReadingTimeLabelDom);
                messageReadingTimeInputDom.numberbox({
                    width: 'calc(100% - 129px)',
                    range: '[1, 600000]',
                    validator: true,
                    required: true,
                    autofill: false,
                    precision: 0
                });
                messageReadingTimeInputDom.addClass("ui-state-disabled").attr("disabled", true);
            }
        } else {
            //移除流服务使用的服务信息
            $this.find(".stream-api-desc").remove();
            //移除流服务使用的其它服务信息
            $this.find(".sync-api-desc").show();
            $this.find(".async-api-desc").show();
            //服务别名编辑
            loadServiceAlias();
            var tempoBaseUrl = rowData.type == 'sync' ? urlPrefix + "/webapi/ai/model/sync/" + rowData.id : urlPrefix + "/webapi/ai/model/async/execute/" + rowData.id;
            serviceGrid.find('[name=async-test-data-url]').text(tempoBaseUrl);
        }

        //服务名称的编辑
        var box = serviceGrid.find('td[name="serviceName"]').empty();
        var input = $('<input name="name" />').val(TempoMineUtils.decodeHTML(row.name)).appendTo(box);
        input.validatebox({
            required: true,
            width: '100%',
            maxLength: 60,
            validator: true,
            autofill: false
        });
        input.addClass("ui-state-disabled").attr("disabled", true);

        //接口说明的编辑
        var IDescript = serviceGrid.find('td[name="async-test-data-explain"]').empty();
        var inputDes = $('<input name="IDesName" />').val(TempoMineUtils.decodeHTML(row.interDescript)).appendTo(IDescript);
        inputDes.validatebox({
            required: true,
            width: '100%',
            maxLength: 60,
            validator: true,
            autofill: false
        });
        inputDes.addClass("ui-state-disabled").attr("disabled", true);
    };

    /**
     * 保存页面后重新渲染
     */
    var configInitSave = function () {
        editStatus.serviceInfo = false;

        var that = $serviceInfo.find('.app-container-left-head-btngroups');
        that.empty();
        $("<span class='ui-icon tempo-ui-icon tempo-ui-icon-rename'></span>").appendTo(that);
        $("<span>" + locale("mine.publish-btn-edit") + "</span>").appendTo(that);
        that.css("color", "#666");

        bindServiceInfoEvent();

        serviceGrid.find('td[name="serviceName"]').find("input").val(TempoMineUtils.decodeHTML(row.name)).addClass("ui-state-disabled").attr("disabled", true);
        if (row.type != 'stream') {
            loadServiceAlias();
        } else {
            //设置消费条数取消编辑
            serviceGrid.find("#tempo-consumption-num").attr("disabled", true);
            //数据上限（条）取消编辑
            serviceGrid.find("input[name='tempo-data-online']").addClass("ui-state-disabled").attr("disabled", true);
            //消息读取时间（ms）取消编辑
            serviceGrid.find("input[name='tempo-message-reading-time']").addClass("ui-state-disabled").attr("disabled", true);
        }
        serviceGrid.find('td[name="async-test-data-explain"]').find("input").val(TempoMineUtils.decodeHTML(row.interDescript)).addClass("ui-state-disabled").attr("disabled", true);
        if (window.location.href.indexOf("view/outcome") != -1) {
            Eventbus.trigger('updateName.service', row);
        }
    };

    /**
     * 编辑服务配置页面
     */
    var editServiceInfo = function () {
        editStatus.serviceInfo = true;
        serviceGrid.find("input[name='name']").validatebox("option", "maxLength", 60);
        serviceGrid.find("input[name='IDesName']").validatebox("option", "maxLength", 60);
        var _this = this;

        //初始保存取消按钮
        $(this).empty();
        $(this).unbind("mouseover").unbind("mouseout").unbind("click");
        var sureBtn = $('<span>' + locale('mine.save') + '</span>').appendTo($(this));
        sureBtn.css("padding-right", "20px").css("color", "#337BFF");
        var cancleBtn = $('<span>' + locale('mine.publish-dialog-cancel') + '</span>').appendTo($(this));
        cancleBtn.css("color", "#666");

        //服务名称的编辑
        var nameInput = serviceGrid.find('td[name="serviceName"]').find("input");
        nameInput.removeClass("ui-state-disabled").attr("disabled", false);

        //设置消费条数
        var consumptionNumDom = serviceGrid.find("#tempo-consumption-num");
        //数据上限（条）
        var dataOnlineInputDom = serviceGrid.find("input[name='tempo-data-online']");
        //消息读取时间（ms）
        var messageReadingTimeInputDom = serviceGrid.find("input[name='tempo-message-reading-time']");

        if (row.type != 'stream') {
            //服务别名编辑
            var aliasBox = serviceGrid.find('td[name="async-test-data-alias"]').empty();
            var aliasInput = $('<input name="serviceAlias" />').val(row.serviceAlias).appendTo(aliasBox);
            //服务别名校验
            aliasInput.validatebox({
                required: false,
                width: '100%',
                maxLength: 60,
                validator: true,
                autofill: false,
                tip: TempoUtils.locale("aiview.serviceAlias"),
                valids: [/^\w{1,60}$/]
            });
        } else {
            //设置消费条数编辑
            consumptionNumDom.attr("disabled", false);
            //数据上限（条）编辑
            dataOnlineInputDom.removeClass("ui-state-disabled").attr("disabled", false);
            //消息读取时间（ms）编辑
            messageReadingTimeInputDom.removeClass("ui-state-disabled").attr("disabled", false);
        }

        //接口说明的编辑
        var descInput = serviceGrid.find('td[name="async-test-data-explain"]').find("input");
        descInput.removeClass("ui-state-disabled").attr("disabled", false);

        sureBtn.unbind('click').bind('click', function (e) {
            var $clickDom = $(_this);
            if (!serviceGrid.formValidate()) {
                TempoUtils.showTip(TempoUtils.locale("aiview.configtip"));
                return;
            }
            //保存事件
            var rowNew = TempoUtils.clone(row);
            //服务名称
            rowNew.name = controller.serviceDialog.find('input[name=name]').val();
            //服务别名
            rowNew.serviceAlias = controller.serviceDialog.find('input[name=serviceAlias]').val() || "";
            //接口说明
            rowNew.interDescript = controller.serviceDialog.find('input[name=IDesName]').val();
            var flowParams;
            if (row.type != 'stream') {
                flowParams = resPar.filter(function (v) {
                    if (v.paramName != "system.appId") {
                        return true;
                    }
                })
            } else {
                //流服务保存服务信息
                flowParams = resPar.filter(function (v) {
                    //过滤系统参数
                    if (v.paramName != "system.appId") {
                        if (v.$configStreamServiceInfo$ != null) {
                            var parse = JSON.parse(v.$configStreamServiceInfo$);
                            parse.setConsumptionNum = controller.serviceDialog.find("#tempo-consumption-num").prop("checked") ? "true" : "false";
                            parse.dataOnline = controller.serviceDialog.find("input[name='tempo-data-online']").val();
                            parse.messageReadingTime = controller.serviceDialog.find("input[name='tempo-message-reading-time']").val();
                            v.$configStreamServiceInfo$ = JSON.stringify(parse);
                            return true;
                        }
                        return true;
                    }
                });
            }
            rowNew.flowParams = JSON.stringify(flowParams);
            window.resPar = flowParams;
            flowArray = getFlowArray();
            Eventbus.trigger("saveApiServiceConfig.mine", rowNew, true, function (data) {
                if (window.location.href.indexOf("view/outcome") != -1) {
                    $("#ca-name").text(TempoMineUtils.decodeHTML(rowNew.name));
                }
                if (data && data.status) {
                    row = rowNew;
                    //保存页面后的重新渲染
                    configInitSave.call($clickDom);
                    scrollChange();
                } else {
                    $("<div/>").alert({
                        msg: TempoUtils.locale("mine.publish-savefailed") + data.error,
                        height: 180,
                        width: 400
                    });
                }
            });
        });

        cancleBtn.unbind('click').bind('click', function (e) {
            serviceGrid.find('td[name="serviceName"]').find("input").val(TempoMineUtils.decodeHTML(row.name)).addClass("ui-state-disabled").attr("disabled", true);
            if (row.type != 'stream') {
                loadServiceAlias();
            } else {
                var setConsumptionNum = "true";
                var dataOnline = 10;
                var messageReadingTime = 1000;
                //获取流服务服务信息的值
                resPar.map(function (v) {
                    if (v.$configStreamServiceInfo$ != null) {
                        var json = JSON.parse(v.$configStreamServiceInfo$);
                        setConsumptionNum = json.setConsumptionNum;
                        dataOnline = json.dataOnline;
                        messageReadingTime = json.messageReadingTime;
                    }
                });
                //设置消费条数取值
                serviceGrid.find("#tempo-consumption-num").checkbox("option", "checked", setConsumptionNum == "true");
                //设置消费条数取消编辑
                serviceGrid.find("#tempo-consumption-num").attr("disabled", true);
                var dataOnlineInputDom = serviceGrid.find("input[name='tempo-data-online']");
                //设置数据上限（条）取值
                dataOnlineInputDom.val(dataOnline);
                //设置数据上限（条）取消编辑
                dataOnlineInputDom.addClass("ui-state-disabled").attr("disabled", true);
                //设置消息读取时间（ms）取值
                serviceGrid.find("input[name='tempo-message-reading-time']").val(messageReadingTime);
                //设置消息读取时间（ms）取消编辑
                serviceGrid.find("input[name='tempo-message-reading-time']").addClass("ui-state-disabled").attr("disabled", true);
                var dataOnlineLabelDom = serviceGrid.find("#tempo-data-online-label");
                //隐藏或显示数据上限（条）
                if (setConsumptionNum == "true") {
                    dataOnlineLabelDom.show();
                    dataOnlineInputDom.show();
                } else {
                    dataOnlineLabelDom.hide();
                    dataOnlineInputDom.hide();
                }
            }
            serviceGrid.find('td[name="async-test-data-explain"]').find("input").val(TempoMineUtils.decodeHTML(row.interDescript)).addClass("ui-state-disabled").attr("disabled", true);
            serviceGrid.find("input[name='name']").validatebox("option", "maxLength", 120);
            serviceGrid.find("input[name='IDesName']").validatebox("option", "maxLength", 120);
            serviceGrid.formValidate();

            editStatus.serviceInfo = false;

            cancleBtn.unbind("mouseover").unbind("mouseout").unbind("click");

            $(_this).empty();
            $("<span class='ui-icon tempo-ui-icon tempo-ui-icon-rename'></span>").appendTo($(_this));
            $("<span>" + locale("mine.publish-btn-edit") + "</span>").appendTo($(_this));
            e.stopPropagation();
            bindServiceInfoEvent();
            scrollChange();
        }).unbind("mouseover").bind("mouseover", function (e) {
            cancleBtn.css("color", "#337bff")
        }).unbind("mouseout").bind("mouseout", function (e) {
            cancleBtn.css("color", "#666")
        });
        scrollChange();
    };

    /**
     * 绑定服务信息配置按钮的相关事件
     * mouseover、mouseout、click
     */
    var bindServiceInfoEvent = function () {
        $serviceInfo.find('span.app-container-left-head-btngroups').unbind('mouseover').bind('mouseover', function (e) {
            $(this).attr("style", "color: #337bff");
            $(this).find(".tempo-ui-icon-rename").addClass("tempo-ui-icon-blue");
        }).unbind('mouseout').bind('mouseout', function (e) {
            $(this).attr("style", "color: #666");
            $(this).find(".tempo-ui-icon-rename").removeClass("tempo-ui-icon-blue");
        }).unbind('click').bind('click', function (e) {
            //当服务开启时，服务配置服务
            if (!!row.launchState && row.launchState != 'NONE') {
                $("<div/>").alert({msg: locale('aiview.stop-first')});
                return;
            }
            if (!editStatus.serviceInfo) {
                editServiceInfo.call(this);//初始化配置页面
            }
        });
    };

    /**
     * 初始化服务信息页面
     */
    var initServiceInfo = function () {
        initServiceInfoPage(row);
        bindServiceInfoEvent();
    };


    /**
     * 初始化授权信息
     */
    var initLicenseInfoPage = function () {
        if ("stream" == row.type) {
            return;
        }
        authGrid.datagrid({
            datatype: "local",
            pagination: false,
            rowNum: 100000,
            multiselect: true,
            shrinkToFit: true,
            fit: true,
            colNames: ['id', TempoUtils.locale("mine.clientName"), TempoUtils.locale("mine.kehubiaoshi"), TempoUtils.locale("mine.diaoyongma"), "描述", "操作"],
            colModel: [{
                name: 'id',
                index: 'id',
                hidden: true
            }, {
                name: 'name',
                index: 'name',
                sortable: false,
                // add 2022-9-30 limy 将证书名进行转义
                formatter: function (value) {
                    if (value != "" && value != undefined && value != null) {
                        return TempoUtils.htmlEscape(value)
                    }
                    return "";
                }
            }, {
                name: 'key',
                index: 'key',
                sortable: false
            }, {
                name: 'secret',
                index: 'secret',
                sortable: false
            }, {
                name: 'description',
                index: 'description',
                sortable: false,
                // add 2022-9-30 limy 将证书内容进行转义
                formatter: function (value) {
                    if (value != "" && value != undefined && value != null) {
                        return TempoUtils.htmlEscape(value)
                    }
                    return "";
                }
            }, {
                name: 'action',
                index: 'action',
                sortable: false,
                formatter: function (cellvalue, options, rowObject) {
                    var html = "<span onclick='copyToClip(\"{itemInfo}\")' copy-info-id='" + options.rowId + "' style='cursor: pointer; color: #337BFF'>复制证书信息</span>";
                    var itemInfo = 'key: ' + rowObject.key + ' secret: ' + rowObject.secret;
                    html = html.replace("{itemInfo}", itemInfo);
                    return html;
                }
            }],
            onSelectRow: function (rowId, status, event) {
                var selectAllBtn = $license.find(".ui-jqgrid-hdiv").find("table").find("th:nth-child(1)").find("input[role=checkbox]");
                //兼容手动全选
                if (authGrid.datagrid("getSelectRowIds").length === authGrid.datagrid("getRowData").length) {
                    selectAllBtn.checkbox('option', 'checked', true);
                    //selectAllBtn.trigger("click");
                } else {
                    selectAllBtn.checkbox('option', 'checked', false);
                }
            },
        });

        authGrid.parent().parent().prev().find("#license-info-table_name").bind("click", function () {
            authGrid.parent().parent().css("height", authGrid[0].offsetHeight);
        });

        //修改全选按钮样式
        var selectAll = $license.find("input[role='checkbox']");
        selectAll.parent().removeClass("ui-th-div");
        var progress = $("<div/>").tempoprogressbar();
        if (row) {
            $.ajax({
                url: contextPath + "/api/ai/mine/webapi/list-auth-app?date="
                    + new Date().getTime(),
                data: {
                    serviceid: row.id
                },
                async: false,
                success: function (result) {
                    authGrid.datagrid('clearGridData');
                    authGrid.datagrid('addJSONData', result.data);
                    //判断是否有数据
                    if (authGrid.datagrid("getRowData").length === 0) {
                        //禁用全选按钮
                        var selectAllBtn = $license.find(".ui-jqgrid-hdiv").find("table").find("th:nth-child(1)").find("input[role=checkbox]");
                        selectAllBtn.checkbox("option", "checked", false);
                        selectAllBtn.next().addClass("ui-state-disabled").attr("disabled", true);
                    } else {
                        //禁用全选按钮
                        var selectAllBtn = $license.find(".ui-jqgrid-hdiv").find("table").find("th:nth-child(1)").find("input[role=checkbox]");
                        selectAllBtn.checkbox("option", "checked", false);
                        selectAllBtn.next().removeClass("ui-state-disabled").attr("disabled", false);
                    }
                    progress.tempoprogressbar("destroy");
                }
            })
        }
        $license.find(".ui-jqgrid-resize-ltr").css("display", "none");
        authGrid.parent().parent().css("height", authGrid[0].offsetHeight);
        scrollChange();
    };

    /**
     * 保存授权码
     * @param rs
     */
    var saveAuth = function (rs) {
        authCodes = rs;
    };

    /**
     * 保存服务信息
     */
    var saveServiceAuth = function (dialog, service) {
        var mask = $("<div/>").tempoprogressbar();
        var auths = authGrid.datagrid('getRowData');
        var authArr = [];
        var codes = [];
        if (auths && auths.length > 0) {
            for (var m = 0; m < auths.length; m++) {
                authArr.push(auths[m].id);
                codes.push(auths[m]);
            }
        }
        ;
        if (authData.addIds.length == 0 && authData.removeIds.length == 0) {
            mask.tempoprogressbar("close");
            saveAuth(codes);
            return;
        }

        $.ajax({
            url: contextPath + "/api/ai/mine/webapi/save-auth",
            data: {
                serviceid: service.id,
                addIds: authData.addIds.join(","),
                removeIds: authData.removeIds.join(",")
            },
            success: function (result) {
                mask.tempoprogressbar("close");
                saveAuth(codes);
            }
        })
    };

    /**
     * 新增授权窗口 保存
     */
    var saveAuthConfig = function (pdialog, dialog) {
        if (pdialog.datagrid("getRowData").length === 0) {
            //禁用全选按钮
            var selectAllBtn = $license.find(".ui-jqgrid-hdiv").find("table").find("th:nth-child(1)").find("input[role=checkbox]");
            selectAllBtn.next().removeClass("ui-state-disabled").attr("disabled", false);
        }

        var grid = dialog.find('.auth_Grid');
        var rowData = grid.datagrid("getSelectRowData");
        if (rowData != null && rowData.length > 0) {
            var authGrid = pdialog;
            authGrid.datagrid('addJSONData', rowData);
            authGrid.parent().parent().css("height", authGrid[0].offsetHeight);
            //判断是否勾选上全选
            var selectAllBtn = $license.find(".ui-jqgrid-hdiv").find("table").find("th:nth-child(1)").find("input[role=checkbox]");
            if (selectAllBtn.checkbox('option', 'checked')) {
                //如果是全选，则全部选中
                var allData = authGrid.datagrid("getRowIds");
                var selectedIds = authGrid.datagrid("getCheckedRowIds");

                for (var i = 0; i < allData.length; i++) {
                    if (selectedIds.indexOf(allData[i]) === -1) {
                        authGrid.datagrid("setSelection", allData[i], true);
                    }
                }
            }
            scrollChange();
            var ids = rowData.map(function (r) {
                return r.id;
            });
            // 过滤添加未删除的id
            var addIds = ids.filter(function (value) {
                return authData.removeIds.filter(function (x) {
                    return x == value;
                }).length == 0;
            });
            // 移除已经删除的id，防止重复删除添加
            var removeIds = authData.removeIds.filter(function (value) {
                return ids.filter(function (x) {
                    return x == value;
                }).length == 0;
            });
            authData.removeIds = removeIds;
            authData.addIds.push(addIds);
            saveServiceAuth(pdialog, row);
        }
    };

    /**
     * 新增授权窗口 列表
     */
    var initAuthCodeGrid = function (dialog, datas) {
        var grid = dialog.find('.auth_Grid');
        grid.data('data', datas);
        grid.datagrid({
            datatype: "local",
            data: datas,
            pagination: false,
            rowNum: 100000,
            multiselect: true,
            fit: true,
            rownumbers: true,
            colNames: ['id',
                'key',
                'secret',
                '证书名称',
                '描述'
            ],
            colModel: [{
                name: 'id',
                index: 'id',
                hidden: true
            }, {
                name: 'key',
                index: 'key',
                hidden: true
            }, {
                name: 'secret',
                index: 'secret',
                hidden: true
            }, {
                name: 'name',
                index: 'name',
                formatter: function (value) {
                    if (value != "" && value != undefined && value != null) {
                        return TempoUtils.htmlEscape(value)
                    }
                    return "";
                }
            }, {
                name: 'description',
                index: 'description',
                formatter: function (value) {
                    if (value != "" && value != undefined && value != null) {
                        return TempoUtils.htmlEscape(value)
                    }
                    return "";
                }
            }],
            onSelectRow: function (rowId, status, event) {
                var selectAllBtn = $("#auth_Dialog").find(".ui-jqgrid-hdiv").find("table").find("th:nth-child(2)").find("input[role=checkbox]");
                //兼容手动全选
                if (grid.datagrid("getSelectRowIds").length === grid.datagrid("getRowData").length) {
                    selectAllBtn.checkbox('option', 'checked', true);
                    //selectAllBtn.trigger("click");
                } else {
                    selectAllBtn.checkbox('option', 'checked', false);
                }
            },
        });
    };

    /**
     * 新增授权窗口
     */
    var showAuthGrid = function (pdialog, datas) {
        var dialog = $("<div/>", {
            "id": 'auth_Dialog'
        });
        $('<table>').addClass('auth_Grid').appendTo(dialog);
        dialog.dialog({
            width: 500,
            height: 350,
            autoOpen: true,
            title: TempoUtils.locale("mine.shouquanliebiao"),
            modal: true,
            close: function () {
                dialog.dialog("destroy");
            },
            open: function () {
                initAuthCodeGrid(dialog, datas);
            },
            buttons: [{
                text: TempoUtils.locale('mine.publish-dialog-sure'),
                click: function () {
                    saveAuthConfig(pdialog, dialog);
                    dialog.dialog("close");
                }
            }, {
                text: TempoUtils.locale('mine.publish-dialog-cancel'),
                click: function () {
                    dialog.dialog("close");
                }
            }]
        });
    };

    /**
     * 服务授权列表 取消授权
     */
    var cancelAuth = function (dialog) {
        var serviceRow = row;
        var grid = dialog;
        var rowData = grid.datagrid("getSelectRowData");
        if (rowData && rowData.length > 0) {

            $("<div>").confirm({
                msg: TempoUtils.locale("mine.shifouquanxiaoshouquan"),
                ok: function () {
                    var selectRowIds = TempoUtils.clone(grid.datagrid("getGridParam", "selarrrow"));
                    if (selectRowIds && selectRowIds.length > 0) {
                        for (var m = 0; m < selectRowIds.length; m++) {
                            var rowid = selectRowIds[m];
                            var row = grid.datagrid('getRowData', rowid);
                            authData.removeIds.push(row.id);
                            grid.datagrid('delRowData', rowid);
                            authGrid.parent().parent().css("height", authGrid[0].offsetHeight);
                            //判断是否有数据
                            if (authGrid.datagrid("getRowData").length === 0) {
                                //禁用全选按钮
                                var selectAllBtn = $license.find(".ui-jqgrid-hdiv").find("table").find("th:nth-child(1)").find("input[role=checkbox]");
                                selectAllBtn.checkbox("option", "checked", false);
                                selectAllBtn.next().addClass("ui-state-disabled").attr("disabled", true);
                            }

                            scrollChange();
                            authData.addIds.filter(function (x) {
                                return x != row.id
                            });
                        }
                    }
                    saveServiceAuth(dialog, serviceRow);
                }
            });
        } else {
            $("<div>").alert({
                msg: TempoUtils.locale("mine.zhishaoxuanzeyitiaoshuju")
            });
        }
    };

    /**
     * 初始化授权信息绑定的事件
     */
    var bindLicenseInfoEvent = function () {
        if ("stream" == row.type) {
            return;
        }
        $license.find('a.add-authorization-button').button({
            click: function () {
                if (!!row.launchState && row.launchState != 'NONE') {
                    $("<div/>").alert({msg: locale('aiview.stop-first')});
                    return;
                }
                authData.removeIds = [];
                authData.addIds = [];
                $.ajax({
                    url: contextPath + "/api/ai/mine/webapi/list-all-app?date=" + new Date().getTime(),
                    data: {},
                    type: 'POST',
                    success: function (result) {
                        if (result && result.success) {
                            var auths = authGrid.datagrid('getRowData');
                            if (auths && auths.length > 0) {
                                var arr = result.data.filter(function (item) {
                                    for (var m = 0; m < auths.length; m++) {
                                        if (auths[m].id == item.id) {
                                            return false;
                                        }
                                    }
                                    if ("SYSTEM" == item.type) {
                                        return false;
                                    }
                                    return true;
                                });
                                showAuthGrid(authGrid, arr);
                            } else {
                                var arr = result.data.filter(function (item) {
                                    if ("SYSTEM" == item.type) {
                                        return false;
                                    }
                                    return true;
                                });
                                showAuthGrid(authGrid, arr);
                            }

                        } else {
                            $("<div/>").alert({
                                msg: TempoUtils.locale("mine.shouquanmaerror")
                            });
                        }
                    }
                })
            }
        });

        $license.find('a.remove-authorization-button').button({
            click: function () {
                if (!!row.launchState && row.launchState != 'NONE') {
                    $("<div/>").alert({msg: locale('aiview.stop-first')});
                    return;
                }
                cancelAuth(authGrid);
            }
        });
    };

    /**
     * 初始化授权信息
     */
    var initLicenseInfo = function () {
        if ("stream" == row.type) {
            $license.remove();
            $that.find(".app-config-container-right").find('a[navTo="#license-info"]').parent().remove();
        } else {
            initLicenseInfoPage();
            bindLicenseInfoEvent();
        }
    };

    /**
     * 初始化实例列表
     * 只有同步服务时才会有实例列表
     */
    var initInstanceInfoPage = function (service) {
        if ("sync" != service.type) {
            return;
        }
        //初始化实例列表
        instanceGrid.datagrid({
            multiselect: true,
            datatype: "json",
            url: contextPath + "/api/ai/mine/getInstanceList",
            mtype: 'POST',
            postData: {serviceId: serviceId},
            fit: true,
            colNames: [
                'IP',
                '端口',
                '最近调用时间',
                '累计次数'
            ],
            colModel: [{
                name: 'IP',
                editable: false,
                sortable: false
            }, {
                name: 'PORT',
                editable: false,
                sortable: false
            }, {
                name: 'RUNTIME',
                editable: false,
                sortable: false
            }, {
                name: 'CISHU',
                editable: false,
                sortable: false
            }],
            loadComplete: function (data) {
                //修改全选按钮样式
                var selectAll = $instance.find("input[role='checkbox']");
                selectAll.parent().removeClass("ui-th-div");
                $instance.find(".ui-jqgrid-resize-ltr").css("display", "none");
                instanceGrid.parent().parent().css("height", instanceGrid[0].offsetHeight);

                //判断是否有数据
                if (instanceGrid.datagrid("getRowData").length === 0) {
                    //禁用全选按钮
                    var selectAllBtn = $instance.find(".ui-jqgrid-hdiv").find("table").find("th:nth-child(1)").find("input[role=checkbox]");
                    selectAllBtn.checkbox("option", "checked", false);
                    selectAllBtn.next().addClass("ui-state-disabled").attr("disabled", true);
                } else {
                    //禁用全选按钮
                    var selectAllBtn = $instance.find(".ui-jqgrid-hdiv").find("table").find("th:nth-child(1)").find("input[role=checkbox]");
                    selectAllBtn.next().removeClass("ui-state-disabled").attr("disabled", false);
                }

                scrollChange();
            },
            onSelectRow: function (rowId, status, event) {
                //兼容手动全选
                if (instanceGrid.datagrid("getSelectRowIds").length === instanceGrid.datagrid("getRowData").length) {
                    var selectAllBtn = $instance.find(".ui-jqgrid-hdiv").find("table").find("th:nth-child(1)").find("input[role=checkbox]");
                    selectAllBtn.trigger("click");
                }
            }
        });
        instanceGrid.parent().parent().prev().find("#instance-info-table_IP,#instance-info-table_PORT,#instance-info-table_RUNTIME,#instance-info-table_CISHU").bind("click", function () {
            instanceGrid.parent().parent().css("height", instanceGrid[0].offsetHeight);
        });
    };

    /**
     * 获取消息数据并进行表格的初始化重新渲染
     * @param serviceId 服务ID
     * @param isProcess 是否增加遮罩
     */
    var getMessageDataWithInitTable = function (serviceId, isProcess) {
        if (isProcess) {
            var process = $("<div/>").tempoprogressbar();
        }
        //获取消息信息数据
        $.ajax({
            url: contextPath + "/api/ai/mine/stream/get-message-data",
            type: 'post',
            data: {
                serviceId: serviceId
            },
            success: function (rs) {
                if (rs.success && rs.data) {
                    var data = rs.data;
                    //主题名称
                    var topic = data.topic;
                    //消费组ID
                    var groupId = data.groupId;
                    //分区数据
                    var partDataList = data.partDataList;
                    //分区数据长度
                    var length = partDataList.length;
                    //获取tbody元素
                    var tbodyDom = messageGrid.find("tbody");
                    //把tbodyDom下的所有Dom元素清空
                    tbodyDom.empty();
                    for (var i = 0; i < partDataList.length; i++) {
                        //获取分区行数据
                        var partData = partDataList[i];
                        //追加行数据
                        var trDom = $("<tr></tr>").appendTo(tbodyDom);
                        //追加主题名称和消费组ID
                        if (i == 0) {
                            $("<td class='formLayoutTit resTableLeft' rowspan='" + length + "'>" +
                                "<div style='white-space: normal;word-break: break-all;'>" + topic + "</div></td>").appendTo(trDom);
                            $("<td class='formLayoutTit resTableLeft' rowspan='" + length + "'>" +
                                "<div style='white-space: normal;word-break: break-all;'>" + groupId + "</div></td>").appendTo(trDom);
                        }
                        //分区数
                        $("<td class='formLayoutTit resTableLeft'><label>" + partData.partNum + "</label></td>").appendTo(trDom);
                        //开始位置
                        $("<td class='formLayoutTit resTableLeft'><label>" + partData.startPositionNum + "</label></td>").appendTo(trDom);
                        //结束位置
                        $("<td class='formLayoutTit resTableLeft'><label>" + partData.endPositionNum + "</label></td>").appendTo(trDom);
                        //偏移量
                        $("<td id='message-info-table-offset-" + partData.partNum + "' class='formLayoutTit resTableLeft'>" +
                            "<label>" + partData.offsetNum + "</label></td>").appendTo(trDom);
                        //未消费
                        $("<td class='formLayoutTit resTableLeft'><label>" + partData.noConsumedNum + "</label></td>").appendTo(trDom);
                    }
                }
                scrollChange();
            },
            complete: function () {
                if (isProcess) {
                    process.tempoprogressbar("destroy");
                }
            },
        });
    }

    /**
     * 初始化消息信息表格
     * 只有流服务时才会有消息信息表格
     */
    var initMessageInfoTable = function (service) {
        //获取消息数据并进行表格的初始化重新渲染
        getMessageDataWithInitTable(service.id, false);
        //初始化刷新按钮的点击事件
        $message.find(".tempo-ui-icon-refresh").unbind("click").bind("click", function () {
            //获取消息数据并进行表格的初始化重新渲染
            getMessageDataWithInitTable(service.id, true);
        });
    }

    /**
     * 检查可编辑区域的状态
     */
    var checkBlockStatus = function (message) {
        if (editStatus.serviceInfo) {
            $("<div/>").alert({
                msg: message + "，服务信息处于编辑状态"
            });
            return false;
        }
        if ("stream" == row.type && editStatus.messageInfo) {
            $("<div/>").alert({
                msg: message + "，消息信息处于编辑状态"
            });
            return false;
        }
        if (editStatus.envInfo) {
            $("<div/>").alert({
                msg: message + "，环境参数配置处于编辑状态"
            });
            return false;
        }
        if (editStatus.flowParams) {
            $("<div/>").alert({
                msg: message + "，流程参数配置处于编辑状态"
            });
            return false;
        }
        if (editStatus.limit) {
            $("<div/>").alert({
                msg: message + "，Python资源限制处于编辑状态"
            });
            return false;
        }
        return true;
    };

    /**
     * 绑定实例信息的事件
     */
    var bindInstanceInfoEvent = function () {
        $instance.find('a.add-instance-button').button({
            click: function () {
                if (!checkBlockStatus("无法添加实例")) {
                    return;
                }
                //服务启动模式
                var mode = envTable.find('select[name=mode-select]').selectmenu("getValue");
                //线程数/管理CPU个数
                var cpu = envTable.find('input[name=manage-cpu-num-input]').val();
                //内存（GB）/管理内存（GB）
                var mem = envTable.find('input[name=manage-memory-input]').val();
                //执行器个数
                var exeProcessNum = envTable.find('input[name=executor-num-input]').val();
                //运行CPU个数
                var totalExecutorCores = envTable.find('input[name=run-cpu-num-input]').val();
                //运行内存（GB）
                var executorMemory = envTable.find('input[name=run-memory-input]').val();
                //管理GPU个数
                var gpu = envTable.find('input[name=gpu]').val();
                //缓存设置
                var cacheType = envTable.find('select[name=cache-config-select]').selectmenu("getValue");
                //Python资源限制CPU个数
                var limitExtendCpu = limitGrid.find('input[name=limitExtendCpuInput]').val();
                //Python资源限制内存(GB)
                var limitExtendMemory = limitGrid.find('input[name=limitExtendMemoryInput]').val();
                var requestId = "";
                if (authCodes == null || authCodes && authCodes.length == 0) {
                    TempoUtils.showTip(TempoUtils.locale("aiview.configtip2"));
                    return;
                }
                if (authCodes.length != 0) {
                    requestId = window.btoa(authCodes[0].clientCode + "#" + authCodes[0].skCode + "#" + new Date().getTime());
                } else {
                    requestId = window.btoa(new Date().getTime());
                }
                var flowParam = "[]";
                if (flowArray != undefined && flowArray != null) {
                    flowParam = JSON.stringify(flowArray);
                }
                var param = {
                    mode: mode || row.mode,
                    cpu: cpu || 2,
                    mem: mem || 2,
                    //执行器个数
                    exeProcessNum: exeProcessNum || 1,
                    //运行CPU个数
                    totalExecutorCores: totalExecutorCores || 2,
                    //运行内存（GB）
                    executorMemory: executorMemory || 2,
                    //管理GPU个数
                    gpu: gpu || 0,
                    //缓存设置
                    cacheType: cacheType || "MEMORY_AND_DISK",
                    //Python资源限制CPU个数
                    limitExtendCpu: limitExtendCpu || 2,
                    //Python资源限制内存(GB)
                    limitExtendMemory: limitExtendMemory || 2,
                    requestId: requestId,
                    //流程参数
                    flowparam: flowParam,
                };
                $instance.find(".add-instance-button").addClass("ui-state-disabled").attr("disabled", true);
                $.postJson({
                    url: contextPath + '/api/ai/app/model/start/' + serviceId,
                    data: param,
                    success: function (result) {
                        var msg = "实例正在启动中，稍后请刷新实例列表！";
                        if (!result.success) {
                            msg = result.message;
                        }
                        var top = $('body').height() / 2 - 115;
                        var left = $('body').width() / 2 - 150;
                        $('body').append('<div id="toolTip" tabindex="-1" role="dialog" class="ui-dialog ui-corner-all ui-widget ui-widget-content ui-front ui-dialog-buttons ui-draggable tempo-dialog tempo-alert-wrap" aria-describedby="ui-id-51" aria-labelledby="ui-id-52" style="height: auto; width: 300px; top: ' + top + 'px; left: ' + left + 'px; display: block; z-index: 135;">' +
                            '<div class="ui-dialog-titlebar ui-corner-all ui-widget-header ui-helper-clearfix ui-draggable-handle">' +
                            '<span id="ui-id-52" class="ui-dialog-title">提示</span>' +
                            '<button type="button" id="buttondelete" class="tempo-button ui-button ui-corner-all ui-widget ui-button-icon-only ui-dialog-titlebar-close" title="" style="height: 28px; line-height: 26px;">' +
                            '<span class="ui-button-icon ui-icon tempo-ui-icon tempo-ui-icon-delete"></span><span class="ui-button-icon-space"> </span></button></div>' +
                            '<div class="tempo-alert ui-dialog-content ui-widget-content" id="ui-id-51" style="width: auto;min-height: 0px;max-height: none;height: 108px;padding-bottom: 0px;">' +
                            '<div style="display: table; width: 100%; height: 68%;"><p>' + msg + '</p></div>' +
                            '<div style="color:rgb(195,184,184)">注：若实例添加失败，请前往Hadoop管理平台查看日志。</div></div><div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"><div class="ui-dialog-buttonset">' +
                            '<button type="button" id="buttonOK" class="tempo-button ui-button ui-corner-all ui-widget" style="height: 28px; line-height: 26px;">确定</button></div></div></div>')
                        $('body').append('<div id="toolTip1" class="ui-widget-overlay ui-front" style="z-index: 101;"></div>');
                        $('body').find('#buttonOK').click(function () {
                            $('body').find('#toolTip').remove();
                            $('body').find("#toolTip1").remove();
                        });
                        $('body').find('#buttondelete').click(function () {
                            $('body').find('#toolTip').remove();
                            $('body').find("#toolTip1").remove();
                        });
                        myId = row.id;
                        if (result.success) {
                            updateMyStatus("start", null);
                            updateStatus("start", true, "", 0);
                        }
                        $('body').find(".add-instance-button").removeClass("ui-state-disabled").attr("disabled", false);
                    }
                })
            }
        });

        $('a.remove-instance-button').button({
            click: function () {
                var rowIds = TempoUtils.clone(instanceGrid.datagrid("getSelectRowIds"));
                if (!rowIds || rowIds.length <= 0) {
                    var msg = '请至少选择一条数据操作';
                    $("<div/>").alert({
                        msg: msg
                    });
                    return;
                }
                var ipPorts = instanceGrid.datagrid("getSelectRowData");
                var allData = instanceGrid.datagrid("getRowData");
                $.ajax({
                    url: contextPath + "/api/ai/mine/deleteInstance",
                    type: 'post',
                    data: {serviceId: serviceId, ipPort: JSON.stringify(ipPorts)},
                    async: false,
                    success: function (rs) {
                        var msg = "服务正在停止，请稍等！";
                        if (!rs.success) {
                            msg = rs.message;
                        }
                        $("<div/>").alert({
                            msg: msg
                        });
                        updateStatusLoop(serviceId, function () {
                            instanceGrid.datagrid("reloadGrid");
                            scrollChange();
                            //判断是否有数据
                            if (instanceGrid.datagrid("getRowData").length === 0) {
                                //禁用全选按钮
                                var selectAllBtn = $instance.find(".ui-jqgrid-hdiv").find("table").find("th:nth-child(1)").find("input[role=checkbox]");
                                selectAllBtn.checkbox("option", "checked", false);
                                selectAllBtn.next().addClass("ui-state-disabled").attr("disabled", true);
                            }
                        }, "sync");
                        if (ipPorts.length == allData.length) {
                            myId = row.id;
                            updateMyStatus("stop", null);
                            updateStatus("stop", false, "", 0);
                        }
                    }
                });
            }
        });

        $instance.find(".tempo-ui-icon-refresh").unbind("click").bind("click", function () {
            instanceGrid.datagrid("reloadGrid");
            scrollChange();
        });
    };

    /**
     * 初始化实例
     */
    var initInstanceInfo = function () {
        if ("sync" == row.type) {
            initInstanceInfoPage(row);
            bindInstanceInfoEvent();
        } else {
            $instance.remove();
            $that.find(".app-config-container-right").find('a[navTo="#instance-info"]').parent().remove();
        }
    };

    /**
     * 绑定消息信息的事件
     */
    var bindMessageInfoEvent = function () {
        //配置按钮的事件--添加权限
        $that.find(".message-info").find('span.message-info-edit').unbind('mouseover').bind('mouseover', function (e) {
            $(this).attr("style", "color: #337bff");
            $(this).find(".tempo-ui-icon-rename").addClass("tempo-ui-icon-blue");
        }).unbind('mouseout').bind('mouseout', function (e) {
            $(this).attr("style", "color: #666");
            $(this).find(".tempo-ui-icon-rename").removeClass("tempo-ui-icon-blue");
        }).unbind('click').bind('click', function (e) {
            if (!!row.launchState && row.launchState != 'NONE') {
                $("<div/>").alert({msg: locale('aiview.stop-first')});
                return;
            }
            if (!editStatus.messageInfo) {
                //初始化配置页面
                editMessageInfo.call(this);
            }
        });
    }

    /**
     * 初始化消息配置（流服务专属）
     */
    var initMessageInfo = function () {
        if ("stream" == row.type) {
            initMessageInfoTable(row);
            bindMessageInfoEvent();
        } else {
            $message.remove();
            $that.find(".app-config-container-right").find('a[navTo="#message-info"]').parent().remove();
        }
    };

    /**
     * 初始化环境参数
     * @returns {boolean}
     */
    var initEnvParamsInfoPage = function () {
        if (!getEnvParamsHtml()) {
            return false;
        }
        scrollChange();
    };

    /**
     * 构建异步服务云模式的表格
     */
    var buildAsyncCloudHtml = function () {
        var html = "";
        html += '<tr>' +
            '<td class="app-config-env-td-label"><label for="driverCpu">管理CPU个数</label></td>' +
            '<td class="app-config-env-td-label"><label for="manageMemory">管理内存（GB）</label></td>' +
            '<td class="app-config-env-td-label"><label>执行器个数</label></td>' +
            '</tr>' +
            '<tr>' +
            '<td name="manage-cpu-num">1</td>' +
            '<td name="manage-memory">1</td>' +
            '<td name="executor-num">1</td>' +
            '</tr>';
        html += '<tr>' +
            '<td class="app-config-env-td-label"><label>运行CPU个数</label></td>' +
            '<td class="app-config-env-td-label"><label>运行内存（GB）</label></td>' +
            '<td class="app-config-env-td-label"><label>缓存设置</label></td>' +
            '</tr>' +
            '<tr>' +
            '<td name="run-cpu-num">1</td>' +
            '<td name="run-memory">1</td>' +
            '<td name="cache-config">1</td>' +
            '</tr>';
        html += '<tr>' +
            '<td class="app-config-env-td-label" sign="gpu"><label>管理GPU个数</label></td>' +
            '</tr>' +
            '<tr>' +
            '<td name="gpu" sign="gpu">0</td>' +
            '</tr>';
        return html;

    };

    /**
     * 构建异步服务本地的表格
     */
    var buildAsyncLocalHtml = function () {
        var html = "";
        html += '<tr>' +
            '<td class="app-config-env-td-label"><label for="driverCpu">线程数</label></td>' +
            '<td class="app-config-env-td-label"><label for="manageMemory">内存（GB）</label></td>' +
            '<td class="app-config-env-td-label" sign="gpu"><label>管理GPU个数</label></td>' +
            '</tr>' +
            '<tr>' +
            '<td name="manage-cpu-num">1</td>' +
            '<td name="manage-memory">1</td>' +
            '<td name="gpu" sign="gpu">0</td>' +
            '</tr>';

        return html;
    };

    /**
     * 构建同步服务或流服务的表格
     */
    var buildSyncOrStreamHtml = function () {
        var html = "";
        html += '<tr>' +
            '<td class="app-config-env-td-label"><label >执行环境</label></td>' +
            '<td class="app-config-env-td-label"><label for="driverCpu">线程数</label></td>' +
            '<td class="app-config-env-td-label"><label for="manageMemory">内存（GB）</label></td>' +
            '</tr>' +
            '<tr>' +
            '<td name="mode">本地</td>' +
            '<td name="manage-cpu-num">1</td>' +
            '<td name="manage-memory">1</td>' +
            '</tr>';
        html += '<tr hideClass="app-config-env-tr-label-yarn">' +
            '<td class="app-config-env-td-label"><label>执行器个数</label></td>' +
            '<td class="app-config-env-td-label"><label>运行CPU个数</label></td>' +
            '<td class="app-config-env-td-label"><label>运行内存（GB）</label></td>' +
            '</tr>' +
            '<tr hideClass="app-config-env-tr-label-yarn">' +
            '<td name="executor-num">1</td>' +
            '<td name="run-cpu-num">1</td>' +
            '<td name="run-memory">1</td>' +
            '</tr>';
        html += '<tr>' +
            '<td class="app-config-env-td-label" hideClass="app-config-env-td-label-yarn"><label>缓存设置</label></td>' +
            '<td class="app-config-env-td-label" sign="gpu"><label>管理GPU个数</label></td>' +
            '</tr>' +
            '<tr>' +
            '<td name="cache-config" hideClass="app-config-env-td-label-yarn">MEMORY_AND_DISK</td>' +
            '<td name="gpu" sign="gpu">0</td>' +
            '</tr>';
        return html;
    }

    /**
     * 获取环境参数的html
     * @returns {boolean}
     */
    var getEnvParamsHtml = function () {

        //获取配置参数
        var configResources = resPar.filter(function (v) {
            if (v.$configResources$ != null) {
                return true;
            }
        });
        //获取流程类型
        var type = row.type;

        if (configResources.length > 0) {
            var json = JSON.parse(configResources[0]["$configResources$"]);
            if (Object.keys(json).length == 0) {
                return false;
            }
            if (type == "async") {
                if (json.executors) {
                    $(buildAsyncCloudHtml()).appendTo(envTable.find("tbody"));
                    envTable.find('td[name="manage-cpu-num"]').html(json.cpu || 2);
                    envTable.find('td[name="manage-memory"]').html(json.mem || 2);
                    envTable.find('td[name="executor-num"]').html(json.executors);
                    envTable.find('td[name="run-cpu-num"]').html(json.execcpu);
                    envTable.find('td[name="run-memory"]').html(json.execmemory);
                    envTable.find('td[name="cache-config"]').html(json.cacheconfig);
                } else {
                    $(buildAsyncLocalHtml()).appendTo(envTable.find("tbody"));
                    envTable.find('td[name="manage-cpu-num"]').html(json.cpu || 2);
                    envTable.find('td[name="manage-memory"]').html(json.mem || 2);
                }
            } else {
                //初始化执行环境
                var mode = json.mode || 'SYNC_ON_LOCAL';
                //默认为本地执行
                if (!EXCUTE_MODE[mode]) {
                    mode = "SYNC_ON_LOCAL";
                }
                //构建同步服务或流服务的表格
                $(buildSyncOrStreamHtml()).appendTo(envTable.find("tbody"));
                envTable.find('td[name="manage-cpu-num"]').html(json.cpu || 2);
                envTable.find('td[name="manage-memory"]').html(json.mem || 2);
                envTable.find('td[name="executor-num"]').html(json.executors || 1);
                envTable.find('td[name="run-cpu-num"]').html(json.execcpu || 2);
                envTable.find('td[name="run-memory"]').html(json.execmemory || 2);
                envTable.find('td[name="cache-config"]').html(json.cacheconfig || "MEMORY_AND_DISK");
                envTable.find('td[name="mode"]').html(EXCUTE_MODE[mode]);
            }

            //判断是否开启GPU
            if (json.gpu) {
                envTable.find('td[sign="gpu"]').show();
                $(envTable.find('td[name="gpu"]')).text(json.gpu || 0);
            } else {
                envTable.find('td[sign="gpu"]').remove();
            }

            //清除空的tr
            var trs = envTable.find("tbody").find("tr");
            for (var i = 0; i < trs.length; i++) {
                if ($(trs[i]).html() === "") {
                    $(trs[i]).css("display", "none");
                }
            }

            //编辑管理CPU个数或者线程数
            var $mcn = $env.find('td[name="manage-cpu-num"]');
            if ($mcn && $mcn.length > 0) {
                var mcnValue = $mcn.text();
                $mcn.empty();
                var $mcnInput = $('<input name="manage-cpu-num-input"/>').val(mcnValue).appendTo($mcn);
                $mcnInput.numberbox({
                    required: true,
                    autofill: false,
                    min: 1,
                    precision: 0
                }).addClass("ui-state-disabled").attr("disabled", true);
            }
            //编辑管理内存或者内存
            var $mm = $env.find('td[name="manage-memory"]');
            if ($mm && $mm.length > 0) {
                var mmValue = $mm.text();
                $mm.empty();
                var $mmInput = $('<input name="manage-memory-input" />').val(mmValue).appendTo($mm);
                $mmInput.numberbox({
                    required: true,
                    autofill: false,
                    min: 1,
                    precision: 0
                }).addClass("ui-state-disabled").attr("disabled", true);
            }
            //编辑执行器个数
            var $en = $env.find('td[name="executor-num"]');
            if ($en && $en.length > 0) {
                var enValue = $en.text();
                $en.empty();
                var $enInput = $('<input name="executor-num-input" />').val(enValue).appendTo($en);
                $enInput.numberbox({
                    required: true,
                    autofill: false,
                    min: 1,
                    precision: 0
                }).addClass("ui-state-disabled").attr("disabled", true);
            }
            //编辑运行内存个数
            var $rcn = $env.find('td[name="run-cpu-num"]');
            if ($rcn && $rcn.length > 0) {
                var rcnValue = $rcn.text();
                $rcn.empty();
                var $rcnInput = $('<input name="run-cpu-num-input" />').val(rcnValue).appendTo($rcn);
                $rcnInput.numberbox({
                    required: true,
                    autofill: false,
                    min: 1,
                    precision: 0
                }).addClass("ui-state-disabled").attr("disabled", true);
            }
            //编辑运行内存
            var $rm = $env.find('td[name="run-memory"]');
            if ($rm && $rm.length > 0) {
                var rmValue = $rm.text();
                $rm.empty();
                var $rmInput = $('<input name="run-memory-input" />').val(rmValue).appendTo($rm);
                $rmInput.numberbox({
                    required: true,
                    autofill: false,
                    min: 1,
                    precision: 0
                }).addClass("ui-state-disabled").attr("disabled", true);
            }

            //编辑GPU
            if (json.gpu) {
                var $gpu = $env.find('td[name="gpu"]');
                if ($gpu && $gpu.length > 0) {
                    var gpuValue = $gpu.text();
                    $gpu.empty();
                    var $gpuInput = $('<input name="gpu" />').val(gpuValue).appendTo($gpu);
                    $gpuInput.numberbox({
                        required: true,
                        autofill: false,
                        min: 0,
                        precision: 0
                    }).addClass("ui-state-disabled").attr("disabled", true);
                }
            }

            //编辑缓存设置
            var $cc = $env.find('td[name="cache-config"]');
            if ($cc && $cc.length > 0) {
                var ccValue = $cc.text();
                $cc.empty();
                var $ccSelect = $('<select name="cache-config-select" />').appendTo($cc);
                var values = [];
                values.push({name: "NONE", value: 'NONE'},
                    {name: 'DISK_ONLY', value: 'DISK_ONLY'},
                    {name: 'DISK_ONLY_2', value: 'DISK_ONLY_2'},
                    {name: 'MEMORY_ONLY', value: 'MEMORY_ONLY'},
                    {name: 'MEMORY_ONLY_2', value: 'MEMORY_ONLY_2'},
                    {name: 'MEMORY_ONLY_SER', value: 'MEMORY_ONLY_SER'},
                    {name: 'MEMORY_ONLY_SER_2', value: 'MEMORY_ONLY_SER_2'},
                    {name: 'MEMORY_AND_DISK', value: 'MEMORY_AND_DISK'},
                    {name: 'MEMORY_AND_DISK_2', value: 'MEMORY_AND_DISK_2'},
                    {name: 'MEMORY_AND_DISK_SER', value: 'MEMORY_AND_DISK_SER'},
                    {name: 'MEMORY_AND_DISK_SER_2', value: 'MEMORY_AND_DISK_SER_2'},
                    {name: 'OFF_HEAP', value: 'OFF_HEAP'});
                for (var i in values) {
                    var value = values[i];
                    $('<option>').text(value.name).attr('value', value.value).appendTo($ccSelect);
                }
                $ccSelect.selectmenu().selectmenu('setValue', ccValue).selectmenu("option", "disabled", true);
            }
            //编辑执行环境
            var $mode = $env.find('td[name="mode"]');
            if ($mode && $mode.length > 0) {
                var modeValue = $mode.text();
                $mode.empty();
                var $modeSelect = $('<select name="mode-select" />').appendTo($mode);
                if (row.type == "sync" || row.type == "stream") {
                    //同步和流时应该判断系统是否支持yarn 支持的则可以切集群
                    $.ajax({
                        url: contextPath + "/api/ai/mine/getClusterParams",
                        type: 'post',
                        async: false,
                        success: function (rs) {
                            var result = rs.data;
                            var values = [];
                            values.push({
                                name: "本地",
                                value: 'SYNC_ON_LOCAL'
                            });
                            if (result && result.masterType.startsWith('yarn')) {
                                values.push({
                                    name: "集群",
                                    value: 'SYNC_ON_YARN'
                                });
                            }
                            if (result && result.masterType.startsWith('k8s')) {
                                values.push({
                                    name: "k8s",
                                    value: 'SYNC_ON_K8S'
                                });
                            }
                            values.reverse();
                            for (var i in values) {
                                var value = values[i];
                                $('<option>').text(value.name).attr('value', value.value).appendTo($modeSelect);
                            }
                            //执行环境下拉框初始化
                            $modeSelect.selectmenu({
                                change: function (event, selected) {
                                    var val = selected.item.value;
                                    //通过模式判断环境参数配置输入框隐藏或显示
                                    envInfoHideOrShowByMode(val);
                                }
                            }).selectmenu("option", "disabled", true);
                        }
                    });
                    //初始化环境参数配置模块
                    envInfoHideOrShowByMode(EXCUTE_MODE[modeValue]);
                }
                $modeSelect.selectmenu().selectmenu('setValue', EXCUTE_MODE[modeValue]).selectmenu("option", "disabled", true);
            }
            return true;
        } else {
            console.error('Parse param error: ', resPar);
        }
        return false;
    };

    /**
     * 通过模式判断环境参数配置输入框隐藏或显示
     * @param mode
     */
    var envInfoHideOrShowByMode = function (mode) {
        if ("SYNC_ON_LOCAL" == mode) {
            //本地执行需要屏蔽无用的参数
            $env.find('tr[hideClass="app-config-env-tr-label-yarn"]').hide();
            $env.find('td[hideClass="app-config-env-td-label-yarn"]').hide();
            //本地执行需要修改输入框文字
            $env.find('label[for="driverCpu"]').text("线程数");
            $env.find('label[for="manageMemory"]').text("内存（GB）");
        } else {
            //集群执行需要显示参数
            $env.find('tr[hideClass="app-config-env-tr-label-yarn"]').show();
            $env.find('td[hideClass="app-config-env-td-label-yarn"]').show();
            //集群执行需要修改输入框文字
            $env.find('label[for="driverCpu"]').text("管理CPU个数");
            $env.find('label[for="manageMemory"]').text("管理内存（GB）");
        }
    }

    /**
     * 编辑消息信息
     */
    var editMessageInfo = function () {
        //更新服务信息编辑状态
        editStatus.messageInfo = true;

        //表格偏移量处于编辑状态
        var offsetTdList = messageGrid.find("td[id^='message-info-table-offset-']");

        for (var i = 0; i < offsetTdList.length; i++) {
            var offsetTd = $(offsetTdList[i]);
            //获取偏移量label
            var offsetLabel = offsetTd.find("label");
            //获取偏移量
            var offset = Number(offsetLabel.text());
            //将旧的偏移量保存到offsetTd中
            offsetTd.attr("offset", offset);
            //获取未消费label
            var offsetNoConsumed = offsetTd.next();
            //获取未消费
            var noConsumed = Number(offsetNoConsumed.text());
            //总数
            var maxNum = offset + noConsumed;
            //将元素清空
            offsetTd.empty();
            //初始化输入框
            var offsetInputDom = $('<input name="tempo-offset-input" maxNum="' + maxNum + '"/>').val(offset).appendTo(offsetTd);
            offsetInputDom.numberbox({
                min: 0,
                validator: true,
                required: true,
                autofill: false,
                precision: 0,
                width: "95%",
                customNumValidate: function (value) {
                    var inputValue = Number(value);
                    var input = $(this);
                    //获取输入框可输入最大值
                    var maxNum = input.attr("maxNum");
                    //输入超过最大值进行自定义提示
                    if (inputValue > maxNum) {
                        input.numberbox("setOptionsTip", "请输入小于偏移量+未消费的整数");
                        input.numberbox("response", false, "请输入小于偏移量+未消费的整数");
                        return false;
                    }
                    return true;
                }
            });
        }

        var _this = this;
        //隐藏刷新按钮
        $(this).prev().hide();
        //初始保存取消按钮
        $(this).empty();
        $(this).unbind("mouseover").unbind("mouseout").unbind("click");
        var sureBtn = $('<span>' + locale('mine.save') + '</span>').appendTo($(this)).css("padding-right", "20px").css("color", "#337BFF");
        var cancleBtn = $('<span>' + locale('mine.publish-dialog-cancel') + '</span>').appendTo($(this)).css("color", "#666");

        //取消按钮事件绑定
        cancleBtn.unbind('click').bind('click', function (e) {
            editStatus.messageInfo = false;
            //表格偏移量处于非编辑状态
            var offsetTdList = messageGrid.find("td[id^='message-info-table-offset-']");
            for (var i = 0; i < offsetTdList.length; i++) {
                var offsetTd = $(offsetTdList[i]);
                //获取旧的偏移量
                var offset = offsetTd.attr("offset");
                //将元素清空
                offsetTd.empty();
                //初始化label
                $("<label>" + offset + "</label>").appendTo(offsetTd);
            }
            cancleBtn.unbind("mouseover").unbind("mouseout").unbind("click");
            //显示刷新按钮
            $(_this).prev().show();
            $(_this).empty();
            $("<span class='ui-icon tempo-ui-icon tempo-ui-icon-rename'></span>").appendTo($(_this));
            $("<span>" + locale("mine.publish-btn-edit") + "</span>").appendTo($(_this));
            e.stopPropagation();
            bindMessageInfoEvent();
        }).unbind("mouseover").bind("mouseover", function (e) {
            cancleBtn.css("color", "#337bff");
        }).unbind("mouseout").bind("mouseout", function (e) {
            cancleBtn.css("color", "#666");
        });

        //点击按钮事件绑定（消息信息编辑保存不进行服务审计日志的保存）
        sureBtn.unbind('click').bind('click', function (e) {
            if (!messageGrid.formValidate()) {
                TempoUtils.showTip(TempoUtils.locale("aiview.configtip"));
                return;
            }
            editStatus.messageInfo = false;
            //表格偏移量处于非编辑状态
            var offsetTdList = messageGrid.find("td[id^='message-info-table-offset-']");
            //保存分区数组
            var partNumList = [];
            //保存偏移量数组
            var offsetList = [];
            for (var i = 0; i < offsetTdList.length; i++) {
                var offsetTd = $(offsetTdList[i]);
                //获取ID
                var id = offsetTd.attr("id");
                //获取分区
                var partNum = id.split("-")[id.split("-").length - 1];
                partNumList.push(partNum);
                //获取input
                var input = offsetTd.find("input");
                //获取偏移量
                var offset = input.val();
                offsetList.push(offset);
            }
            var process = $("<div/>").tempoprogressbar();
            //获取消息信息数据
            $.ajax({
                url: contextPath + "/api/ai/mine/stream/update-offset",
                type: 'post',
                async: false,
                data: {
                    serviceId: row.id,
                    partNumList: partNumList.join(","),
                    offsetList: offsetList.join(","),
                },
                success: function (rs) {
                    if (!rs.success) {
                        $("<div/>").alert({
                            msg: "偏移量更新失败：" + rs.message
                        });
                    }
                },
                complete: function () {
                    process.tempoprogressbar("destroy");
                },
            });
            //获取消息数据并进行表格的初始化重新渲染
            getMessageDataWithInitTable(row.id, false);
            e.stopPropagation();
            //保存页面后的重新渲染
            messageInfoInitSave.call($(_this));
        });
    };

    /**
     * 消息信息数据保存页面后的重新渲染
     */
    var messageInfoInitSave = function () {
        var that = $that.find(".message-info").find('.app-container-left-head-btngroups');
        //显示刷新按钮
        that.prev().show();
        that.empty();
        //编辑图标
        $("<span class='ui-icon tempo-ui-icon tempo-ui-icon-rename'></span>").appendTo(that);
        //编辑span
        $("<span>" + locale("mine.publish-btn-edit") + "</span>").appendTo(that);
        that.css("color", "#666");
        bindMessageInfoEvent();
    };

    /**
     * 编辑环境参数
     */
    var editEnvInfo = function () {
        //更新服务信息编辑状态
        editStatus.envInfo = true;

        var that = $that;
        var _this = this;
        var $env = that.find("#tempo-mine-flow-env-info");
        //初始保存取消按钮
        $(this).empty();
        $(this).unbind("mouseover").unbind("mouseout").unbind("click");
        var sureBtn = $('<span>' + locale('mine.save') + '</span>').appendTo($(this)).css("padding-right", "20px").css("color", "#337BFF");
        var cancleBtn = $('<span>' + locale('mine.publish-dialog-cancel') + '</span>').appendTo($(this)).css("color", "#666");

        //编辑管理CPU个数或者线程数
        var $mcn = $env.find('input[name="manage-cpu-num-input"]');
        if ($mcn && $mcn.length > 0) $mcn.removeClass("ui-state-disabled").attr("disabled", false);
        //编辑管理内存或者内存
        var $mm = $env.find('input[name="manage-memory-input"]');
        if ($mm && $mm.length > 0) $mm.removeClass("ui-state-disabled").attr("disabled", false);
        //编辑执行器个数
        var $en = $env.find('input[name="executor-num-input"]');
        if ($en && $en.length > 0) $en.removeClass("ui-state-disabled").attr("disabled", false);
        //编辑运行内存个数
        var $rcn = $env.find('input[name="run-cpu-num-input"]');
        if ($rcn && $rcn.length > 0) $rcn.removeClass("ui-state-disabled").attr("disabled", false);
        //编辑运行内存
        var $rm = $env.find('input[name="run-memory-input"]');
        if ($rm && $rm.length > 0) $rm.removeClass("ui-state-disabled").attr("disabled", false);

        //编辑gpu
        var $gpu = $env.find('input[name="gpu"]');
        if ($gpu && $gpu.length > 0) $gpu.removeClass("ui-state-disabled").attr("disabled", false);

        //编辑缓存设置
        var $cc = $env.find('select[name="cache-config-select"]');
        if ($cc && $cc.length > 0) $cc.selectmenu("option", "disabled", false);
        //编辑执行环境
        var $mode = $env.find('select[name="mode-select"]');
        if ($mode && $mode.length > 0) $mode.selectmenu("option", "disabled", false);

        cancleBtn.unbind('click').bind('click', function (e) {
            editStatus.envInfo = false;
            cancleBtn.unbind("mouseover").unbind("mouseout").unbind("click");
            var configResources = resPar.filter(function (v) {
                if (v.$configResources$ != null) {
                    return true;
                }
            });
            if (configResources.length > 0) {
                editStatus.envInfo = false;

                var json = JSON.parse(configResources[0]["$configResources$"]);
                if (Object.keys(json).length != 0) {
                    //编辑管理CPU个数或者线程数
                    if ($mcn && $mcn.length > 0) $mcn.val(json.cpu || 2).addClass("ui-state-disabled").attr("disabled", true);
                    //编辑管理内存或者内存
                    if ($mm && $mm.length > 0) $mm.val(json.mem || 2).addClass("ui-state-disabled").attr("disabled", true);
                    //编辑执行器个数
                    if ($en && $en.length > 0) $en.val(json.executors || 1).addClass("ui-state-disabled").attr("disabled", true);
                    //编辑运行内存个数
                    if ($rcn && $rcn.length > 0) $rcn.val(json.execcpu || 2).addClass("ui-state-disabled").attr("disabled", true);
                    //编辑运行内存
                    if ($rm && $rm.length > 0) $rm.val(json.execmemory || 2).addClass("ui-state-disabled").attr("disabled", true);
                    //编辑gpu
                    if ($gpu && $gpu.length > 0) $gpu.val(json.gpu || 0).addClass("ui-state-disabled").attr("disabled", true);
                    //编辑缓存设置
                    if ($cc && $cc.length > 0) $cc.selectmenu('setValue', json.cacheconfig || "MEMORY_AND_DISK").selectmenu("option", "disabled", true);
                    //编辑执行环境
                    var modeValue = json.mode || 'SYNC_ON_LOCAL';
                    if ($mode && $mode.length > 0) $mode.selectmenu('setValue', modeValue).selectmenu("option", "disabled", true);
                    //通过模式判断环境参数配置输入框隐藏或显示
                    envInfoHideOrShowByMode(modeValue);
                }
                envTable.formValidate();
                $(_this).empty();
                $("<span class='ui-icon tempo-ui-icon tempo-ui-icon-rename'></span>").appendTo($(_this));
                $("<span>" + locale("mine.publish-btn-edit") + "</span>").appendTo($(_this));
                e.stopPropagation();
                bindEnvParamsInfoEvent();
            }
        }).unbind("mouseover").bind("mouseover", function (e) {
            cancleBtn.css("color", "#337bff")
        }).unbind("mouseout").bind("mouseout", function (e) {
            cancleBtn.css("color", "#666")
        });

        sureBtn.unbind('click').bind('click', function (e) {
            if (!envTable.formValidate()) {
                TempoUtils.showTip(TempoUtils.locale("aiview.configtip"));
                return;
            }
            //保存事件
            var rowNew = TempoUtils.clone(row);
            var configResources = resPar.filter(function (v) {
                if (v.$configResources$ != null) {
                    return true;
                }
            });

            if (configResources.length > 0) {

                var json = JSON.parse(configResources[0]["$configResources$"]);
                //编辑管理CPU个数或者线程数
                var cni = envTable.find('input[name=manage-cpu-num-input]');
                if (json.cpu && cni.length == 1) json.cpu = cni.val();
                //编辑管理内存或者内存
                var mmi = envTable.find('input[name=manage-memory-input]');
                if (json.mem && mmi.length == 1) json.mem = mmi.val();
                //编辑执行器个数
                var eni = envTable.find('input[name=executor-num-input]');
                if (json.executors && eni.length == 1) json.executors = eni.val();
                //编辑运行内存个数
                var rcni = envTable.find('input[name=run-cpu-num-input]');
                if (json.execcpu && rcni.length == 1) json.execcpu = rcni.val();
                //编辑运行内存
                var rmi = envTable.find('input[name=run-memory-input]');
                if (json.execmemory && rmi.length == 1) json.execmemory = rmi.val();
                //编辑缓存设置
                var ccs = envTable.find('select[name=cache-config-select]');
                if (json.cacheconfig && ccs.length == 1) json.cacheconfig = ccs.selectmenu("getValue");
                //编辑执行环境
                var ms = envTable.find('select[name=mode-select]');
                if (json.mode && ms.length == 1) json.mode = ms.selectmenu("getValue");
                //编辑gpu
                var gpu = envTable.find('input[name=gpu]');
                if (json.gpu && gpu.length == 1) json.gpu = gpu.val();
                var flowParams = resPar.filter(function (v) {
                    //过滤系统参数
                    if (v.paramName != "system.appId") {
                        if (v.$configResources$ != null) {
                            v.$configResources$ = JSON.stringify(json);
                            return true;
                        }
                        return true;
                    }
                });
                rowNew.flowParams = JSON.stringify(flowParams);
                window.resPar = flowParams;
                flowArray = getFlowArray();
                Eventbus.trigger("saveApiServiceConfig.mine", rowNew, true, function (data) {
                    if (data && data.status) {
                        row = rowNew;
                        //保存页面后的重新渲染
                        envInitSave.call($(_this));
                    } else {
                        $("<div/>").alert({
                            msg: TempoUtils.locale("mine.publish-savefailed") + data.error,
                            height: 180,
                            width: 400
                        });
                    }
                });
            } else {
                console.error('configResources error: ', configResources);
            }
        });
    };

    /**
     * 保存页面后重新渲染
     */
    var envInitSave = function () {
        editStatus.envInfo = false;

        var that = $that.find(".env-info").find('.app-container-left-head-btngroups');
        that.empty();
        $("<span class='ui-icon tempo-ui-icon tempo-ui-icon-rename'></span>").appendTo(that);
        $("<span>" + locale("mine.publish-btn-edit") + "</span>").appendTo(that);
        that.css("color", "#666");
        bindEnvParamsInfoEvent();
        var envInfoTable = $env.find('.env-info-table');
        if (row.flowParams) {
            //编辑管理CPU个数或者线程数
            var cni = envInfoTable.find('input[name=manage-cpu-num-input]');
            if (cni.length == 1) cni.addClass("ui-state-disabled").attr("disabled", true);
            //编辑管理内存或者内存
            var mmi = envInfoTable.find('input[name=manage-memory-input]');
            if (mmi.length == 1) mmi.addClass("ui-state-disabled").attr("disabled", true);
            //编辑执行器个数
            var eni = envInfoTable.find('input[name=executor-num-input]');
            if (eni.length == 1) eni.addClass("ui-state-disabled").attr("disabled", true);
            //编辑运行内存个数
            var rcni = envInfoTable.find('input[name=run-cpu-num-input]');
            if (rcni.length == 1) rcni.addClass("ui-state-disabled").attr("disabled", true);
            //编辑运行内存
            var rmi = envInfoTable.find('input[name=run-memory-input]');
            if (rmi.length == 1) rmi.addClass("ui-state-disabled").attr("disabled", true);
            //编辑gpu
            var gpu = envInfoTable.find('input[name=gpu]');
            if (gpu.length == 1) gpu.addClass("ui-state-disabled").attr("disabled", true);
            //编辑缓存设置
            var ccs = envInfoTable.find('select[name=cache-config-select]');
            if (ccs.length == 1) ccs.selectmenu("option", "disabled", true);
            //编辑执行环境
            var ms = envInfoTable.find('select[name=mode-select]');
            if (ms.length == 1) ms.selectmenu("option", "disabled", true);
        }
    };

    /**
     * 绑定环境参数时间
     */
    var bindEnvParamsInfoEvent = function () {
        //配置按钮的事件--添加权限
        $that.find(".env-info").find('span.env-info-edit').unbind('mouseover').bind('mouseover', function (e) {
            $(this).attr("style", "color: #337bff");
            $(this).find(".tempo-ui-icon-rename").addClass("tempo-ui-icon-blue");
        }).unbind('mouseout').bind('mouseout', function (e) {
            $(this).attr("style", "color: #666");
            $(this).find(".tempo-ui-icon-rename").removeClass("tempo-ui-icon-blue");
        }).unbind('click').bind('click', function (e) {
            if (!!row.launchState && row.launchState != 'NONE') {
                $("<div/>").alert({msg: locale('aiview.stop-first')});
                return;
            }
            if (!editStatus.envInfo) {
                editEnvInfo.call(this);//初始化配置页面
            }
        });
    };

    /**
     * 初始化环境参数
     */
    var inintEnvParamsInfo = function () {
        initEnvParamsInfoPage();
        bindEnvParamsInfoEvent();
    };

    /**
     * 初始化资源使用情况监控
     * 后续考虑将该块代码提出一个js进行维护
     */
    var initResourceInfoPage = function () {
        resourceGrid.html(getResourceHtml());

        resourceGrid.find("table td").css("border", "1px solid #dddddd").css("text-align", "center ");
        resourceGrid.find("table tr:nth-child(1) td").css("color", "#5b6e85").css("font-weight", "bold")
            .css("border-top", "1px solid #dae0e9").css("border-bottom", "2px solid #dae0e9").css("line-height", "23px");
        resourceGrid.find("table tr:nth-child(3)").css("background", "#f8fafd");

        resourceGrid.find("#content").tabs({
            activate: function (event, ui) {
            }
        });
        ajaxLoadingResources(resourceGrid, null, false);//初始化资源环境监控信息
    };


    /**
     * 获取资源监控html
     * @returns {string}
     */
    var getResourceHtml = function () {
        var html = "<div id='content'> " +
            "<ul id='ul'>" +
            "<li><a href=\"#res-local\"><span>" + TempoUtils.locale("mine.flow_res_local") + "</span></a></li>" +
            "<li><a href=\"#res-cluster\"><span>" + TempoUtils.locale("mine.flow_res_cluster") + "</span></a></li>" +
            "<li><a href=\"#res-curUser\"><span>" + TempoUtils.locale("mine.flow_res_curUser") + "</span></a></li>" +
            "<li><a href=\"#res-monitor\"><span>授权资源</span></a></li>" +
            "</ul>" +
            '<div id="res-local">' +
            '<table class="formLayout" id="resMonitorLocalTable" >' +
            '<tr>' +
            '<td class="formLayoutTit resTableLeft">' +
            '    <label >服务器</label>' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label >' + TempoUtils.locale("mine.flow_res_resource") + '</label>' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label >' + TempoUtils.locale("mine.flow_res_total") + '</label>' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label >' + TempoUtils.locale("mine.flow_res_used") + '</label>' +
            '	</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label >' + TempoUtils.locale("mine.flow_res_left") + '</label>' +
            '</td>' +
            '</tr>' +
            '<tr>' +
            '<td class="formLayoutTit resTableLeft" rowspan="2">' +
            '	<label ></label>' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	' + TempoUtils.locale("mine.flow_res_allCpu") + '' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft" >' +
            '	<label ></label>' +
            '	</td>' +
            '<td class="formLayoutTit resTableLeft" >' +
            '	<label ></label>' +
            '</td>' +
            '</tr>' +
            '<tr>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	' + TempoUtils.locale("mine.flow_res_allMemory") + '' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '	</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '</td>' +
            '</tr>' +
            '</table>' +
            '</div>' +
            '<div id="res-cluster">' +
            '<table class="formLayout" id="resMonitorClusterTable"> ' +
            '<tr>' +
            '<td class="formLayoutTit resTableLeft">' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label >' + TempoUtils.locale("mine.flow_res_total") + '</label>' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label >' + TempoUtils.locale("mine.flow_res_used") + '</label>' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label >' + TempoUtils.locale("mine.flow_res_left") + '</label>' +
            '</td>' +
            '</tr>' +
            '<tr>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	' + TempoUtils.locale("mine.flow_res_allCpu") + '' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '	</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '</td>' +
            '</tr>' +
            '<tr>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	' + TempoUtils.locale("mine.flow_res_allMemory") + '' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '	</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '</td>' +
            '</tr>' +
            '</table>' +
            '</div>' +
            '<div id="res-curUser">' +
            '<table class="formLayout" id="resMonitorCurrentUserTable">' +
            '<tr>' +
            '<td class="formLayoutTit resTableLeft">' +

            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label >' + TempoUtils.locale("mine.flow_res_total") + '</label>' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label >' + TempoUtils.locale("mine.flow_res_used") + '</label>' +
            '	</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label >' + TempoUtils.locale("mine.flow_res_left_can_use") + '</label>' +
            '</td>' +
            '</tr>' +
            '<tr>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	' + TempoUtils.locale("mine.flow_res_allCpu") + '' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '	</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '</td>' +
            '</tr>' +
            '<tr>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	' + TempoUtils.locale("mine.flow_res_allMemory") + '' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '	</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '</td>' +
            '</tr>' +
            '</table>' +
            '</div>' +
            '<div id="res-monitor">' +
            '<table class="formLayout" id="resCurrentResourceTable">' +
            '<tr>' +
            '<td class="formLayoutTit resTableLeft">' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label >' + TempoUtils.locale("mine.flow_res_total") + '</label>' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label >' + TempoUtils.locale("mine.flow_res_used") + '</label>' +
            '	</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label >' + TempoUtils.locale("mine.flow_res_left") + '</label>' +
            '</td>' +
            '</tr>' +
            '<tr>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	' + TempoUtils.locale("mine.flow_res_allCpu") + '' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '	</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '</td>' +
            '</tr>' +
            '<tr>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	' + TempoUtils.locale("mine.flow_res_allMemory") + '' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '	</td>' +
            '<td class="formLayoutTit resTableLeft">' +
            '	<label ></label>' +
            '</td>' +
            '</tr>' +
            '</table>' +
            '</div>' +
            '</div>';
        return html;
    };

    /**
     * tag 标志是否添加遮罩，点击刷新图标触发tagtrue遮罩，点击页签不触发
     * @param resMonitorForm
     * @param mask
     * @param tag
     * @param API
     */
    var ajaxLoadingResources = function (resMonitorForm, mask, tag, API) {
        if (tag == true) {
            mask = $("<div/>").tempoprogressbar();
        }
        var initResMonitorLoacalTable = function (datas) {
            var $table = resMonitorForm.find("#resMonitorLocalTable");
            var keys = Object.keys(datas);
            for (var i = 0; i < keys.length; i++) {
                var row1Array = $table.find("tr:eq(" + (i * 2 + 1) + ") label");
                var row2Array = $table.find("tr:eq(" + (i * 2 + 2) + ") label");
                if (row1Array.length == 0 && row2Array.length == 0) {
                    resMonitorForm.find("#resMonitorLocalTable tbody").append("<tr>" + $table.find("tr:eq(1)").html() + "</tr>");
                    resMonitorForm.find("#resMonitorLocalTable tbody").append("<tr style='background: rgb(248, 250, 253);'>" + $table.find("tr:eq(2)").html() + "</tr>");
                    row1Array = $table.find("tr:eq(" + (i * 2 + 1) + ") label");
                    row2Array = $table.find("tr:eq(" + (i * 2 + 2) + ") label");
                }
                var data = datas[keys[i]];
                var allMemory = data[3].toFixed(2);
                var leftMemory = data[4].toFixed(2);
                var usedMemory = (allMemory - leftMemory).toFixed(2);
                $(row1Array[0]).text(keys[i]);
                $(row1Array[1]).text(data[0]);
                $(row1Array[2]).text(data[1].toFixed(2) + "%");
                $(row1Array[3]).text(data[2].toFixed(2) + "%");
                $(row2Array[0]).text(allMemory);//总内存
                $(row2Array[1]).text(usedMemory);//已使用内存
                $(row2Array[2]).text(leftMemory);//可用内存=已缓存+空闲
            }

        };
        var initResMonitorClusterTable = function (data) {
            var $table = resMonitorForm.find("#resMonitorClusterTable");
            var row1Array = $table.find("tr:eq(1) label");
            var row2Array = $table.find("tr:eq(2) label");
            var allocateGB = (data['allocatedMB'] / 1024).toFixed(2);
            var availableGB = (data['availableMB'] / 1024).toFixed(2);
            var allGB = (Number(allocateGB) + Number(availableGB)).toFixed(2);
            $(row1Array[0]).text(Number(data['allocatedVirtualCores']) + Number(data['availableVirtualCores']));
            $(row1Array[1]).text(data['allocatedVirtualCores']);
            $(row1Array[2]).text(data['availableVirtualCores']);
            $(row2Array[0]).text(allGB);//总内存
            $(row2Array[1]).text(allocateGB);//已使用内存
            $(row2Array[2]).text(availableGB);//可用内存=已缓存+空闲
        };
        var initResCurrentResourceTable = function (data) {
            var $table = resMonitorForm.find("#resCurrentResourceTable");
            var row1Array = $table.find("tr:eq(1) label");
            var row2Array = $table.find("tr:eq(2) label");
            var allGB = data["allMemory"] ? Number(data["allMemory"]).toFixed(2) : "";
            var availableGB = allGB != "" ? (Number(data["allMemory"]) - Number(data['useMemory'])).toFixed(2) : "";
            var allCpu = data["allCpu"] ? Number(data["allCpu"]) : "";
            var availableCpu = allGB != "" ? Number(data["allCpu"]) - Number(data['useCpu']) : "";
            $(row1Array[0]).text(allCpu);
            $(row1Array[1]).text(data['useCpu']);
            $(row1Array[2]).text(availableCpu);
            $(row2Array[0]).text(allGB);//总内存
            $(row2Array[1]).text(data['useMemory'].toFixed(2));//已使用内存
            $(row2Array[2]).text(availableGB);//可用内存=已缓存+空闲
        };

        /**
         * k8s模式下集群资源监控情况
         * @param data
         */
        var initK8sClusterTable = function (data) {
            var $table = resMonitorForm.find("#resMonitorClusterTable");
            var row1Array = $table.find("tr:eq(1) label");
            var row2Array = $table.find("tr:eq(2) label");
            var allocateGB = (data['executeMemory']).toFixed(2);
            var allGB = (data['k8sTotalMemory']).toFixed(2);
            var availableGB = (Number(allGB) - Number(allocateGB)).toFixed(2);
            $(row1Array[0]).text(data['k8sTotalCpu']);
            $(row1Array[1]).text(data['driverCpu']);
            $(row1Array[2]).text(Number(data['k8sTotalCpu']) - Number(data['driverCpu']));
            $(row2Array[0]).text(allGB);//总内存
            $(row2Array[1]).text(allocateGB);//已使用内存
            $(row2Array[2]).text(availableGB);//可用内存=已缓存+空闲
        }

        var initResMonitorCurrentUserTable = function (data, yarn0) {
            var $table = resMonitorForm.find("#resMonitorCurrentUserTable");
            var row1Array = $table.find("tr:eq(1) label");
            var row2Array = $table.find("tr:eq(2) label");
            var maxMermoryGB = (data['maxMermory'] / 1024).toFixed(2);
            var usedMermoryGB = (data['usedMemory'] / 1024).toFixed(2);
            var leftMermoryGB = (maxMermoryGB - usedMermoryGB).toFixed(2);
            var leftCores = data['maxCores'] - data['usedCores'];
            //队列不存在，资源显示可能有问题，需要特殊处理，修改56118bug
            if (yarn0 != null) {
                if (parseFloat(leftCores) > parseFloat(yarn0["availableVirtualCores"])) {
                    leftCores = yarn0["availableVirtualCores"];
                    data['usedCores'] = data['maxCores'] - leftCores;
                }
                if (parseFloat(leftMermoryGB) > parseFloat((yarn0['availableMB'] / 1024).toFixed(2))) {
                    leftMermoryGB = (yarn0['availableMB'] / 1024).toFixed(2);
                    usedMermoryGB = (maxMermoryGB - leftMermoryGB).toFixed(2);
                }
            }

            $(row1Array[0]).text(data['maxCores']);
            $(row1Array[1]).text(data['usedCores']);
            $(row1Array[2]).text(leftCores);
            $(row2Array[0]).text(maxMermoryGB);//总内存
            $(row2Array[1]).text(usedMermoryGB);//已使用内存
            $(row2Array[2]).text(leftMermoryGB);//可用内存=已缓存+空闲
            //赋值当前队列名称
            $resource.find("li[aria-controls=res-curUser]").attr("title", TempoUtils.locale("mine.flow_res_curUserName") + data.fullQueueName)
        };

        $.ajax({
            url: contextPath + "/api/ai/mine/getResMonitor",
            type: 'post',
            success: function (rs) {
                if (mask != null) {
                    if (API) {
                        mask.partprogressbar('close');
                    } else {
                        mask.tempoprogressbar('close');
                    }
                }
                if (rs.Local != null) {
                    initResMonitorLoacalTable(rs.Local);
                }
                if (rs.Yarn != null && rs.k8s == undefined) {
                    if (rs.Yarn[0] != null) {
                        initResMonitorClusterTable(rs.Yarn[0]);
                    } else {
                        resMonitorForm.find("#resMonitorClusterTable").parent().remove();
                        resMonitorForm.find("a[href='#res-cluster']").parent().remove();
                    }
                    if (rs.Yarn[1] != null) {
                        initResMonitorCurrentUserTable(rs.Yarn[1], rs.Yarn[0]);
                    } else {
                        resMonitorForm.find("#resMonitorCurrentUserTable").parent().remove();
                        resMonitorForm.find("a[href='#res-curUser']").parent().remove();
                    }
                } else if (rs.Yarn != null && rs.k8s != undefined && rs.k8s != null) {
                    initK8sClusterTable(rs.k8s);
                    resMonitorForm.find("#resMonitorCurrentUserTable").parent().remove();
                    resMonitorForm.find("a[href='#res-curUser']").parent().remove();
                } else {
                    resMonitorForm.find("#resMonitorClusterTable").parent().remove();
                    resMonitorForm.find("a[href='#res-cluster']").parent().remove();

                    resMonitorForm.find("#resMonitorCurrentUserTable").parent().remove();
                    resMonitorForm.find("a[href='#res-curUser']").parent().remove();
                }
                if (rs.resource != null) {
                    initResCurrentResourceTable(rs.resource);
                } else {
                    resMonitorForm.find("#resCurrentResourceTable").parent().remove();
                    resMonitorForm.find("a[href='#res-monitor']").parent().remove();
                }
            },
            complete: function () {
                if (mask != null) {
                    if (API) {
                        mask.partprogressbar('close');
                    } else {
                        mask.tempoprogressbar('close');
                    }
                }
                scrollChange();
            }
        });
    };

    /**
     * 绑定资源使用情况的事件
     */
    var bindSourceEvent = function () {
        $resource.find(".tempo-ui-icon-refresh").unbind("click").bind("click", function () {
            ajaxLoadingResources(resourceGrid, null, true)
        });
    };

    /**
     * 初始化资源管理
     */
    var initResourceInfo = function () {
        initResourceInfoPage();
        bindSourceEvent();
    };

    /**
     * 初始化Python资源设置
     */
    var initLimitInfoPage = function () {
        $.ajax({
            url: contextPath + "/api/ai/mine/getClusterParams",
            type: 'post',
            success: function (response) {
                var result = response.data;
                //判断系统管理是否开启python资源限制
                var isOpen = result.resourceLimitEnable;
                if (!isOpen) {
                    $limitInfo.remove();
                    $that.find(".app-config-container-right").find('a[navTo="#limit-info"]').parent().remove();
                } else {
                    //获取python资源限制默认参数值
                    var pythonLimitParam = ajaxLoadingPythonLimit();
                    //CPU个数输入框初始化
                    var extendCpuTd = limitGrid.find("td[name=limitExtendCpu]");
                    extendCpuTd.empty();
                    var extendCpuInput = $('<input name="limitExtendCpuInput" />').val(pythonLimitParam.limitExtendCpu).appendTo(extendCpuTd);
                    extendCpuInput.numberbox({
                        range: '[1, 16]',
                        validator: true,
                        required: true,
                        autofill: false,
                        precision: 0,
                    }).addClass("ui-state-disabled").attr("disabled", true);
                    //内存（GB）输入框初始化
                    var extendMemoryTd = limitGrid.find("td[name=limitExtendMemory]");
                    extendMemoryTd.empty();
                    var extendMemoryInput = $('<input name="limitExtendMemoryInput" />').val(pythonLimitParam.limitExtendMemory).appendTo(extendMemoryTd);
                    extendMemoryInput.numberbox({
                        range: '[1, 32]',
                        validator: true,
                        required: true,
                        autofill: false,
                        precision: 0,
                    }).addClass("ui-state-disabled").attr("disabled", true);
                    var configResources = resPar.filter(function (v) {
                        if (v.$configResources$ != null) {
                            return true;
                        }
                    });
                    //服务设置过值回填设置的值
                    if (configResources.length > 0) {
                        var json = JSON.parse(configResources[0]["$configResources$"]);
                        extendCpuInput.val(json.limitCpu || pythonLimitParam.limitExtendCpu);
                        extendMemoryInput.val(json.limitMemory || pythonLimitParam.limitExtendMemory);
                    } else {
                        console.error("initLimitInfo", "the parseing of $configResources$ is error");
                    }
                }
                scrollChange();
            }
        });
    };

    /**
     * 回填资源限制表格的方法
     * @returns {{limitExtendMemory: *, limitExtendCpu: *}}
     */
    var ajaxLoadingPythonLimit = function () {
        var limitExtendCpu = 2;
        var limitExtendMemory = 2;
        $.ajax({
            url: contextPath + "/api/ai/mine/getClusterParams",
            type: 'post',
            async: false,
            success: function (response) {
                var result = response.data;
                limitExtendCpu = result.limitExtendCpu;
                limitExtendMemory = result.limitExtendMemory;
            }
        });
        return {
            "limitExtendCpu": limitExtendCpu,
            "limitExtendMemory": limitExtendMemory
        };
    };

    /**
     * 编辑python资源限制
     */
    var editLimit = function () {
        editStatus.limit = true;

        var _this = this;
        //保存和取消按钮出现
        $(this).empty();
        $(this).unbind("mouseover").unbind("mouseout").unbind("click");
        var sureBtn = $('<span>' + locale('mine.save') + '</span>').appendTo($(this));
        sureBtn.css("padding-right", "20px").css("color", "#337BFF");
        var cancleBtn = $('<span>' + locale('mine.publish-dialog-cancel') + '</span>').appendTo($(this));
        cancleBtn.css("color", "#666");
        //CPU个数
        var extendCpuInput = limitGrid.find("input[name=limitExtendCpuInput]");
        //内存(GB)
        var extendMemoryInput = limitGrid.find("input[name=limitExtendMemoryInput]");
        //原始值
        var extendCpuValue = extendCpuInput.val();
        var extendMemoryValue = extendMemoryInput.val();
        //CPU个数编辑
        extendCpuInput.removeClass("ui-state-disabled").attr("disabled", false);
        //内存(GB)编辑
        extendMemoryInput.removeClass("ui-state-disabled").attr("disabled", false);

        sureBtn.unbind('click').bind('click', function (e) {
            if (!limitGrid.formValidate()) {
                TempoUtils.showTip(TempoUtils.locale("aiview.configtip"));
                return;
            }
            editStatus.limit = false;
            //保存事件
            var rowNew = TempoUtils.clone(row);

            var flowParams = resPar.filter(function (v) {
                //过滤系统参数
                if (v.paramName != "system.appId") {
                    if (v.$configResources$ != null) {
                        var parse = JSON.parse(v.$configResources$);
                        parse.limitCpu = limitGrid.find("input[name=limitExtendCpuInput]").val();
                        parse.limitMemory = limitGrid.find("input[name=limitExtendMemoryInput]").val();
                        v.$configResources$ = JSON.stringify(parse);
                        return true;
                    }
                    return true;
                }
            });
            rowNew.flowParams = JSON.stringify(flowParams);
            window.resPar = flowParams;
            flowArray = getFlowArray();
            Eventbus.trigger("saveApiServiceConfig.mine", rowNew, true, function (data) {
                if (data && data.status) {
                    row = rowNew;
                    //保存页面后的重新渲染
                    limitInitSave.call($(_this));
                } else {
                    $("<div/>").alert({
                        msg: TempoUtils.locale("mine.publish-savefailed") + data.error,
                        height: 180,
                        width: 400
                    });
                }
            });
        });
        cancleBtn.unbind('click').bind('click', function (e) {
            editStatus.limit = false;
            cancleBtn.unbind("mouseover").unbind("mouseout").unbind("click");

            //CPU个数
            extendCpuInput.val(extendCpuValue);
            //内存(GB)
            extendMemoryInput.val(extendMemoryValue);

            limitGrid.formValidate();

            //设置CPU个数取消编辑
            extendCpuInput.addClass("ui-state-disabled").attr("disabled", true);
            //设置内存(GB)取消编辑
            extendMemoryInput.addClass("ui-state-disabled").attr("disabled", true);

            $(_this).empty();
            $("<span class='ui-icon tempo-ui-icon tempo-ui-icon-rename'></span>").appendTo($(_this));
            $("<span>" + locale("mine.publish-btn-edit") + "</span>").appendTo($(_this));
            e.stopPropagation();
            bindLimitEvent();
        }).unbind("mouseover").bind("mouseover", function (e) {
            cancleBtn.css("color", "#337bff")
        }).unbind("mouseout").bind("mouseout", function (e) {
            cancleBtn.css("color", "#666")
        });
    };

    /**
     * Python资源限制页面数据保存后回调
     */
    var limitInitSave = function () {
        var that = $that.find(".limit-info").find('.app-container-left-head-btngroups');
        that.empty();
        $("<span class='ui-icon tempo-ui-icon tempo-ui-icon-rename'></span>").appendTo(that);
        $("<span>" + locale("mine.publish-btn-edit") + "</span>").appendTo(that);
        that.css("color", "#666");
        bindLimitEvent();

        var extendCpuInput = limitGrid.find("input[name=limitExtendCpuInput]");
        //设置CPU个数取消编辑
        extendCpuInput.addClass("ui-state-disabled").attr("disabled", true);

        var extendMemoryInput = limitGrid.find("input[name=limitExtendMemoryInput]");
        //设置内存(GB)取消编辑
        extendMemoryInput.addClass("ui-state-disabled").attr("disabled", true);

    };

    /**
     * 初始化python资源限制的事件
     */
    var bindLimitEvent = function () {
        $limitInfo.find('span.app-container-left-head-btngroups').unbind('mouseover').bind('mouseover', function (e) {
            $(this).attr("style", "color: #337bff");
            $(this).find(".tempo-ui-icon-rename").addClass("tempo-ui-icon-blue");
        }).unbind('mouseout').bind('mouseout', function (e) {
            $(this).attr("style", "color: #666");
            $(this).find(".tempo-ui-icon-rename").removeClass("tempo-ui-icon-blue");
        }).unbind('click').bind('click', function (e) {
            if (!!row.launchState && row.launchState != 'NONE') {
                $("<div/>").alert({msg: locale('aiview.stop-first')});
                return;
            }
            if (!editStatus.limit) {
                editLimit.call(this);
            }
        });
    };

    /**
     * 初始化Python资源限制
     */
    var initLimitInfo = function () {
        initLimitInfoPage();
        bindLimitEvent();
    };

    /**
     * 初始化流程参数
     */
    var initFlowParamInfoPage = function () {
        paramGrid.datagrid({
            datatype: "local",
            data: flowArray,
            pagination: false,
            rowNum: 100000,
            shrinkToFit: true,
            fit: true,
            colNames: ["参数名称", "参数值", "参数说明", "参数类型", "节点类型", "ID", "原先参数值"],
            colModel: [{
                name: 'paramName',
                index: 'paramName',
                sortable: false
            }, {
                name: 'paramValue',
                index: 'paramValue',
                sortable: false,
                formatter: function (cellvalue, options, rowObject) {
                    if (rowObject.paramType && rowObject.paramType === "datasource") {
                        $.ajax({
                            url: contextPath + '/api/ai/node/io/get-datasource-by-code',
                            type: 'post',
                            async: false,
                            data: {
                                code: JSON.stringify([cellvalue])
                            },
                            success: function (data) {
                                try {
                                    cellvalue = data.data[0].name;
                                } catch (e) {
                                    console.log(data);
                                }
                            }
                        });
                        return TempoMineUtils.encodeHTML(cellvalue);
                    } else {
                        return TempoMineUtils.encodeHTML(constFlowParams[cellvalue] || cellvalue);
                    }
                }
            }, {
                name: 'paramDesc',
                index: 'paramDesc',
                sortable: false,
                formatter: function (cellvalue, options, rowObject) {
                    if (cellvalue) {
                        return TempoMineUtils.encodeHTML(cellvalue);
                    } else {
                        return "";
                    }
                }
            }, {
                name: "paramType",
                index: "paramType",
                hidden: true
            }, {
                name: "nodeType",
                index: "nodeType",
                hidden: true
            }, {
                name: "paramId",
                index: "paramId",
                hidden: true
            }, {
                name: 'paramValue',
                index: 'paramValue',
                hidden: true
            }],
            onSelectRow: function (rowId, status, event) {
                $(event.target).parent().removeClass("ui-state-highlight");
            }
        });
        $paramInfo.find(".ui-jqgrid-resize-ltr").css("display", "none");
        paramGrid.parent().parent().css("height", paramGrid[0].offsetHeight);
        scrollChange();
    };

    /**
     * 流程参数页面数据保存后回调
     */
    var flowParamInitSave = function () {
        var that = $that.find(".flowparam-info").find('.app-container-left-head-btngroups');
        that.empty();
        $("<span class='ui-icon tempo-ui-icon tempo-ui-icon-rename'></span>").appendTo(that);
        $("<span>" + locale("mine.publish-btn-edit") + "</span>").appendTo(that);
        that.css("color", "#666");
        bindFlowParamsEvent();

        for (var i = 1; i <= flowArray.length; i++) {
            var paramValueTd = paramGrid.find("tr:nth-child(" + (i + 1) + ")").find("td:nth-child(2)");
            var paramValue = paramValueTd.find("select").selectmenu("getValue");

            var paramType = paramGrid.find("tr:nth-child(" + (i + 1) + ")").find("td:nth-child(4)").text();
            if (paramType && paramType === "datasource") {
                $.ajax({
                    url: contextPath + '/api/ai/node/io/get-datasource-by-code',
                    type: 'post',
                    async: false,
                    data: {
                        code: JSON.stringify([paramValue])
                    },
                    success: function (data) {
                        paramValueTd.empty().text(data.data[0].name);
                    }
                });
            } else {
                paramValueTd.empty().text(constFlowParams[paramValue] || paramValue);
            }
        }
        flowArray = getFlowArray();
    };

    var createFlowParamValueInput = function (paramGrid, paramValueIndex, paramTypeIndex, nodeTypeValue, test) {
        var trs = paramGrid.find("tr");
        for (var i = 1; i < trs.length; i++) {
            var paramValueTd = $(trs[i]).find("td:nth-child(" + paramValueIndex + ")");
            var paramValue = paramValueTd.text().trim();
            paramValueTd.empty();

            var paramValueSelect = $('<select type="pvalue"/>').val(paramValue).appendTo(paramValueTd);
            var pss = [];

            var paramTypeTd = $(trs[i]).find("td:nth-child(" + paramTypeIndex + ")");
            var type = paramTypeTd.text();

            var nodeTypeTd = $(trs[i]).find("td:nth-child(" + nodeTypeValue + ")");
            var nodeType = nodeTypeTd.text();

            if (type == 'datasource') {
                var loadDatasource = function (data) {
                    for (var j = 0; j < data.length; j++) {
                        var dataItem = data[j];
                        // 屏蔽模型数据源、presto数据源、impala数据源
                        if (nodeType == 'readrdbms') {
                            if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1) {
                                continue;
                            }
                        }
                        if (nodeType == 'writerdbms') {
                            if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1 || (dataItem.purpose && dataItem.purpose != "1")) {
                                continue;
                            }
                        }

                        if (nodeType == 'readhive') {
                            if (dataItem.type != 'hive') {
                                continue;
                            }
                        }
                        if (nodeType == 'writehive') {
                            if ('hive' != dataItem.type || (dataItem.purpose && dataItem.purpose != "1")) {
                                continue;
                            }
                        }
                        if (nodeType == "readinfluxdb") {
                            if (!(dataItem.type == "influxdb" || dataItem.type == "influxdb2")) {
                                continue;
                            }
                        }
                        if (nodeType == "readtaosdb") {
                            if (dataItem.type != "taosDB") {
                                continue;
                            }
                        }
                        if (nodeType == "readiotdb") {
                            if (dataItem.type != 'iotdb') {
                                continue;
                            }
                        }
                        if (nodeType == "writeiotdb") {
                            //不是iotdb  或者不能写入
                            if ('iotdb' != dataItem.type || (dataItem.purpose && dataItem.purpose != "1")) {
                                continue;
                            }
                        }

                        pss.push('<option value="' + dataItem.code + '">' + dataItem.name + '</option>')
                    }
                    var html = pss.join('');
                    paramValueSelect.html(html);

                    var pVSWidth = "80%";
                    if (test) {
                        pVSWidth = "218px";
                    }

                    paramValueSelect.selectmenu({
                        editable: false,
                        width: pVSWidth
                    }).selectmenu('setValue', $(trs[i]).find("td:nth-child(7)").text()).selectmenu('refresh');
                };
                if (dataSourceCache['datasource']) {
                    loadDatasource(dataSourceCache['datasource']);
                } else {
                    $.ajax({
                        url: contextPath + '/api/ai/node/io/list-datasources',
                        type: 'post',
                        data: {
                            isFilterWritable: false //是否过滤可写
                        },
                        async: false,
                        success: function (data) {
                            if (data.success) {
                                dataSourceCache['datasource'] = data.data;
                                loadDatasource(dataSourceCache['datasource']);
                            } else {
                                console.error("数据源加载失败");
                                dataSourceCache['datasource'] = [];
                                loadDatasource(dataSourceCache['datasource']);
                            }
                        }
                    });
                }
            } else {
                if (constFlowParams) {
                    for (name in constFlowParams) {
                        pss.push('<option value="' + name + '">' + constFlowParams[name] + '</option>')
                    }
                }

                var html = pss.join('');
                paramValueSelect.html(html);
                var pVSWidth = "80%";
                if (test) {
                    pVSWidth = "218px";
                }
                paramValueSelect.selectmenu({
                    editable: true,
                    width: pVSWidth,
                }).selectmenu('setValue', paramValue);
            }
        }
    };

    /**
     * 编辑流程参数页面
     */
    var editFlowParams = function () {
        editStatus.flowParams = true;

        var _this = this;
        //保存和取消按钮出现
        $(this).empty();
        $(this).unbind("mouseover").unbind("mouseout").unbind("click");
        var sureBtn = $('<span>' + locale('mine.save') + '</span>').appendTo($(this));
        sureBtn.css("padding-right", "20px").css("color", "#337BFF");
        var cancleBtn = $('<span>' + locale('mine.publish-dialog-cancel') + '</span>').appendTo($(this));
        cancleBtn.css("color", "#666");

        createFlowParamValueInput(paramGrid, 2, 4, 5);

        sureBtn.unbind('click').bind('click', function (e) {
            editStatus.flowParams = false;
            //保存事件
            var rowNew = TempoUtils.clone(row);
            var flowParams = [];
            for (var i = 1; i <= flowArray.length; i++) {
                var paramValue = paramGrid.find("tr:nth-child(" + (i + 1) + ")").find("td:nth-child(2)").find("select").selectmenu("getValue");
                var obj = {
                    paramName: paramGrid.find("tr:nth-child(" + (i + 1) + ")").find("td:nth-child(1)").text(),
                    paramValue: paramValue,
                    paramDesc: paramGrid.find("tr:nth-child(" + (i + 1) + ")").find("td:nth-child(3)").text()
                };
                if (TempoMineUtils.disableInputElement(paramValue)) return false;
                if (flowArray[i - 1].paramType) {
                    obj.paramType = paramGrid.find("tr:nth-child(" + (i + 1) + ")").find("td:nth-child(4)").text()
                }
                if (flowArray[i - 1].nodeType) {
                    obj.nodeType = paramGrid.find("tr:nth-child(" + (i + 1) + ")").find("td:nth-child(5)").text()
                }
                if (flowArray[i - 1].paramId) {
                    obj.paramId = paramGrid.find("tr:nth-child(" + (i + 1) + ")").find("td:nth-child(6)").text()
                }
                flowParams.push(obj);
            }

            //将配置参数过滤出来
            var config = resPar.filter(function (v) {
                return v["$configResources$"] || v["$configStreamServiceInfo$"];
            });
            //此处不能删除，异步服务和同步服务保存流程参数时没有$configStreamServiceInfo$属性
            if (config.length === 1) {
                flowParams.push(config[0]);
            }
            //兼容历史，只有新的流服务才会有$configStreamServiceInfo$属性
            if (config.length === 2) {
                flowParams.push(config[0]);
                flowParams.push(config[1]);
            }
            //将系统参数过滤出来
            var systemParam = resPar.filter(function (v) {
                return v["paramName"] == "system.appId";
            });
            if (systemParam.length === 1) {
                flowParams.push(systemParam[0]);
            }
            rowNew.flowParams = JSON.stringify(flowParams);
            window.resPar = flowParams;
            flowArray = getFlowArray();
            Eventbus.trigger("saveApiServiceConfig.mine", rowNew, true, function (data) {
                if (data && data.status) {
                    row = rowNew;
                    //保存页面后的重新渲染
                    flowParamInitSave.call($(_this));
                } else {
                    $("<div/>").alert({
                        msg: TempoUtils.locale("mine.publish-savefailed") + data.error,
                        height: 180,
                        width: 400
                    });
                }
            });
        });
        cancleBtn.unbind('click').bind('click', function (e) {
            editStatus.flowParams = false;
            cancleBtn.unbind("mouseover").unbind("mouseout").unbind("click");
            paramGrid.datagrid("clearGridData");
            paramGrid.datagrid("setGridParam", {datatype: 'local', data: flowArray});
            paramGrid.datagrid("reloadGrid");
            $paramInfo.find(".ui-jqgrid-resize-ltr").css("display", "none");
            paramGrid.parent().parent().css("height", paramGrid[0].offsetHeight);
            scrollChange();

            $(_this).empty();
            $("<span class='ui-icon tempo-ui-icon tempo-ui-icon-rename'></span>").appendTo($(_this));
            $("<span>" + locale("mine.publish-btn-edit") + "</span>").appendTo($(_this));
            e.stopPropagation();
            bindFlowParamsEvent();
        }).unbind("mouseover").bind("mouseover", function (e) {
            cancleBtn.css("color", "#337bff")
        }).unbind("mouseout").bind("mouseout", function (e) {
            cancleBtn.css("color", "#666")
        });
    };

    /**
     * 初始化流程参数事件
     */
    var bindFlowParamsEvent = function () {
        $paramInfo.find('span.app-container-left-head-btngroups').unbind('mouseover').bind('mouseover', function (e) {
            $(this).attr("style", "color: #337bff");
            $(this).find(".tempo-ui-icon-rename").addClass("tempo-ui-icon-blue");
        }).unbind('mouseout').bind('mouseout', function (e) {
            $(this).attr("style", "color: #666");
            $(this).find(".tempo-ui-icon-rename").removeClass("tempo-ui-icon-blue");
        }).unbind('click').bind('click', function (e) {
            if (!!row.launchState && row.launchState != 'NONE') {
                $("<div/>").alert({msg: locale('aiview.stop-first')});
                return;
            }
            if (!editStatus.flowParams) {
                editFlowParams.call(this);//初始化配置页面
            }
        });
    };

    /**
     * 初始化流程参数
     */
    var initFlowParamInfo = function () {
        initFlowParamInfoPage();
        bindFlowParamsEvent();
    };


    /**
     * 初始化请求参数页面
     */
    var initRequestInfoPage = function () {
        if ("stream" === row.type) return;
        requestGrid.datagrid({
            datatype: "local",
            pagination: false,
            rowNum: 100000,
            data: REQUEST_PARAMETERS,
            shrinkToFit: true,
            fit: true,
            colNames: ['名称', "描述"],
            colModel: [{
                name: 'name',
                index: 'name',
                width: '20px',
                sortable: false
            }, {
                name: 'desc',
                index: 'desc',
                sortable: false
            }],
            onSelectRow: function (rowId, status, event) {
                $(event.target).parent().removeClass("ui-state-highlight");
            }
        });
        $requestInfo.find(".ui-jqgrid-resize-ltr").css("display", "none");
        requestGrid.parent().parent().css("height", requestGrid[0].offsetHeight);
        scrollChange();
    };

    var initRequestInfo = function () {
        if ("stream" !== row.type) {
            initRequestInfoPage();
        } else {
            $requestInfo.remove();
            $that.find(".app-config-container-right").find('a[navTo="#request-info"]').parent().remove();
        }
    };

    /**
     * 初始化返回参数页面
     */
    var initResponseInfoPage = function () {
        if ("stream" === row.type) return;
        responseGrid.datagrid({
            datatype: "local",
            pagination: false,
            rowNum: 100000,
            data: RESPONSE_PARAMETERS,
            shrinkToFit: true,
            fit: true,
            colNames: ['名称', "描述"],
            colModel: [{
                name: 'name',
                index: 'name',
                width: '20px',
                sortable: false
            }, {
                name: 'desc',
                index: 'desc',
                sortable: false
            }],
            onSelectRow: function (rowId, status, event) {
                $(event.target).parent().removeClass("ui-state-highlight");
            }
        });
        $responseInfo.find(".ui-jqgrid-resize-ltr").css("display", "none");
        responseGrid.parent().parent().css("height", responseGrid[0].offsetHeight);
        scrollChange();
    };

    /**
     * 初始化返回参数页面
     */
    var initResponseInfo = function () {
        if ("stream" !== row.type) {
            initResponseInfoPage();
        } else {
            $responseInfo.remove();
            $that.find(".app-config-container-right").find('a[navTo="#response-info"]').parent().remove();
        }
    };

    /**
     * 适配页面的放大和缩小
     */
    var initResize = function () {
        $(window).resize(function () {
            setTimeout(function () {
                try {
                    var isAccess = false;
                    //授权块缩放
                    if ($that.find('#license-info-table').length === 1) {
                        authGrid.datagrid("resize");
                        authGrid.parent().parent().css("height", authGrid[0].offsetHeight);
                        isAccess = true;
                    }

                    if ($that.find('#instance-info-table').length === 1 && "sync" == row.type) {
                        instanceGrid.datagrid("resize");
                        instanceGrid.parent().parent().css("height", instanceGrid[0].offsetHeight);
                        isAccess = true;
                    }

                    if ($that.find('#flowparam-info-table').length === 1) {
                        paramGrid.datagrid("resize");
                        paramGrid.parent().parent().css("height", paramGrid[0].offsetHeight);
                        isAccess = true;
                    }

                    if ($that.find('#request-info-table').length === 1 && $that.find('#response-info-table').length === 1 && "stream" !== row.type) {
                        requestGrid.datagrid("resize");
                        requestGrid.parent().parent().css("height", requestGrid[0].offsetHeight);

                        responseGrid.datagrid("resize");
                        responseGrid.parent().parent().css("height", responseGrid[0].offsetHeight);
                        isAccess = true;
                    }
                    if (isAccess) scrollChange();
                } catch (e) {
                }
            }, 200);
        });
    };


    /**
     * 请求服务状态
     * @param fn 回调函数
     * @param uid 服务ID
     */
    var isAlive = function (fn, uid) {
        var id = uid || row.id;
        $.postForm({
            url: contextPath + '/api/ai/app/model/status/' + id,
            success: function (rp) {
                fn(rp.data == 'STARTING' || rp.data == 'RUNNING', rp.data, id);
            }
        });
    };

    /**
     * 更新服务状态信息
     * @param op
     * @param finalTag
     * @param serviceStatus
     * @param counter
     */
    var updateStatus = function (op, finalTag, serviceStatus, counter) {
        var id = row.id;
        if (op == "start") {
            //开启按钮进行禁用
            $containerTop.find('a.start-button').addClass("ui-state-disabled").attr("disabled", true);
        }
        setTimeout(function () {
            var fn = arguments.callee;
            isAlive(function (d, status, thisId) {
                if (d == finalTag && row.id == thisId) {
                    row.launchState = status;
                    if (op == "start") {//status == 'STARTING'
                        setTimeout(function () {
                            var fn = arguments.callee;
                            isAlive(function (d, status, thisId) {
                                if (status == 'STARTING' && row.id == thisId) {
                                    updateStatusLoop(row.id, null, row.type);
                                } else if (status != 'STARTING') {
                                    row.launchState = status;
                                    //更改启动为停止
                                    $containerTop.find('a.start-button').text(TempoUtils.locale("aiview.serviceStop"));
                                    //服务状态为已经启动
                                    $("div[objid='" + row.id + "'] #ca-status").text(TempoUtils.locale("aiview.serviceHasStart"));
                                    $("div[objid='" + row.id + "'] #service_status").text(TempoUtils.locale("aiview.serviceHasStart"));
                                    serviceStatus = TempoUtils.locale("aiview.serviceHasStart");
                                    //Eventbus.trigger('updateserviceStatus.service', serviceStatus,row.id);
                                    instanceGrid.datagrid("reloadGrid");
                                    scrollChange();

                                    //判断是否有数据
                                    if (instanceGrid.datagrid("getRowData").length === 0) {
                                        //禁用全选按钮
                                        var selectAllBtn = $instance.find(".ui-jqgrid-hdiv").find("table").find("th:nth-child(1)").find("input[role=checkbox]");
                                        selectAllBtn.checkbox("option", "checked", false);
                                        //selectAllBtn.next().removeClass("ui-state-disabled");
                                    }
                                }

                            }, id);
                        }, 1000);
                    } else if (op == "stop") {
                        $containerTop.find('a.start-button').text(TempoUtils.locale("aiview.serviceStart"));
                        $("div[objid='" + row.id + "'] #ca-status").text(TempoUtils.locale("aiview.serviceUnStart"));
                        $("div[objid='" + row.id + "'] #service_status").text(TempoUtils.locale("aiview.serviceUnStart"));
                        serviceStatus = TempoUtils.locale("aiview.serviceUnStart");
                        Eventbus.trigger('updateserviceStatus.service', serviceStatus, row.id);
                        $containerTop.find('a.start-button').removeClass("ui-state-disabled").attr("disabled", false);

                        instanceGrid.datagrid("reloadGrid");
                        scrollChange();

                        //判断是否有数据
                        if (instanceGrid.datagrid("getRowData").length === 0) {
                            //禁用全选按钮
                            var selectAllBtn = $instance.find(".ui-jqgrid-hdiv").find("table").find("th:nth-child(1)").find("input[role=checkbox]");
                            selectAllBtn.checkbox("option", "checked", false);
                            selectAllBtn.next().addClass("ui-state-disabled").attr("disabled", true);
                        }
                    }
                } else if (d != finalTag) {
                    counter++;
                    if (op == "start") {
                        $("div[objid='" + row.id + "'] #ca-status").text(TempoUtils.locale("aiview.serviceStarting"));
                        $("div[objid='" + row.id + "'] #service_status").text(TempoUtils.locale("aiview.serviceStarting"));
                        serviceStatus = TempoUtils.locale("aiview.serviceStarting");
                    }
                    if (counter < 30) {
                        setTimeout(fn, 1000);
                    } else {
                        row.launchState = status;
                        if (status != "RUNNING" && status != "STARTING") {
                            $("div[objid='" + row.id + "'] #ca-status").text(TempoUtils.locale("aiview.serviceUnStart"));
                            $("div[objid='" + row.id + "'] #service_status").text(TempoUtils.locale("aiview.serviceUnStart"));
                            serviceStatus = TempoUtils.locale("aiview.serviceStarting");

                            instanceGrid.datagrid("reloadGrid");
                            scrollChange();

                            //判断是否有数据
                            if (instanceGrid.datagrid("getRowData").length === 0) {
                                //禁用全选按钮
                                var selectAllBtn = $instance.find(".ui-jqgrid-hdiv").find("table").find("th:nth-child(1)").find("input[role=checkbox]");
                                selectAllBtn.checkbox("option", "checked", false);
                                selectAllBtn.next().addClass("ui-state-disabled").attr("disabled", true);
                            }
                        } else if (status == "STARTING") {
                            // 继续进行状态查询
                            updateStatusLoop(row.id, null, row.type);
                        }
                        //Eventbus.trigger('updateserviceStatus.service', serviceStatus, row.id);
                    }
                }
            }, id);
        }, 3000);
    };


    /**
     * 监听滚动条移动的位置
     * 1、获取到每一个DIV距离top的高度，
     * 2、计算滚动条的高度，进行比对得出下标
     * 3、点亮右边的按钮
     */
    var scrollChange = function () {
        var $left = $that.find(".app-config-container-left");
        /**
         * 获取所有模块的数组
         */
        var getHeight = function () {
            var $blocks = $left.find("div[sign=block]");
            var len = $blocks.length;
            var data = [];
            for (var i = 0; i < len; i++) {
                var h = $blocks[i].clientHeight;
                if (i == 0) {
                    data[i] = h;
                } else {
                    data[i] = data[i - 1] + h;
                }
            }
            return data;
        };

        arrHeight = getHeight();

        var getIndex = function (top) {
            for (var i = 0; i < arrHeight.length; i++) {
                if (top < arrHeight[i]) {
                    return i;
                }
            }
        };
        $left.parent().unbind("scroll").bind("scroll", function () {
            var $ul = $that.find(".app-config-container-right").find("ul");
            var $liList = $ul.children();
            var len = $liList.length;
            var lis = [];
            for (var i = 0; i < len; i++) {
                if ($liList[i].tagName.toUpperCase() == "LI") {
                    lis.push($liList[i]);
                }
            }
            //根据滚动事件，计算当前应该是哪个模块被激活
            var top = this.scrollTop;
            var index = getIndex(top);
            var liLength = lis.length;
            for (var i = 0; i < liLength; i++) {
                var cls = $(lis[i]).find("a")[0].className;
                if (cls && i != index) {
                    $(lis[i]).find("a").removeClass("light");
                }
                if (i == index) {
                    $(lis[i]).find("a").addClass("light");
                }
            }
        });
    };
    /**
     * 初始化右边列表点击事件，锚点连接
     */
    var initLIInfo = function () {
        var $ul = $that.find(".app-config-container-right").find("ul");
        $ul.find("a.navItems").unbind("click").bind("click", function (e) {
            var navTo = $(this).attr('navTo');
            var $div = $(navTo);
            var top = $div[0].offsetTop || 0;
            $('.app-config-container-body').animate({
                'scroll-top': top
            }, 500);
        });
    };


    /***
     * 复制key到剪切板中
     * @param s 需要赋值的内容
     */
    window.copyToClip = function (s) {
        var aux = document.createElement("input");
        aux.setAttribute("value", s);
        document.body.appendChild(aux);
        aux.select();
        document.execCommand("copy");
        document.body.removeChild(aux);
        $("<div/>").alert({msg: locale('mine.copy_success')});
    };

    /**
     * 初始化成果管理处的服务状态
     */
    var initManageServiceStatus = function () {

        if (row.launchState == 'STARTING') {
            //服务启动中，将启动按钮禁用
            $containerTop.find('a.start-button').addClass("ui-state-disabled").attr("disabled", true);
            //服务启动中，将成果管理处的服务状态变为未启动
            $('span[id="' + row.id + '"]').text(TempoUtils.locale("aiview.serviceStarting"));
        }

        if (row.launchState == 'NONE') {
            //服务未启动，将成果管理处的服务状态变为未启动
            $('span[id="' + row.id + '"]').text(TempoUtils.locale("aiview.serviceUnStart"));
        }

        if (row.launchState == 'RUNNING') {
            //服务已启动，将成果管理处的服务状态变为已启动
            $('span[id="' + row.id + '"]').text(TempoUtils.locale("aiview.serviceHasStart"));
        }

    }

    /**
     * 初始化
     */
    var init = function () {
        initContainerTop();
        initServiceInfo();
        initLicenseInfo();
        initInstanceInfo();
        initMessageInfo();
        inintEnvParamsInfo();
        initResourceInfo();
        initLimitInfo();
        initFlowParamInfo();
        initRequestInfo();
        initResponseInfo();
        initResize();
        setTimeout(scrollChange(), 1000);
        initLIInfo();
        //初始化成果管理处的服务状态
        initManageServiceStatus();
    };

    init();
});